package com.eascs.admin.o2o.loan.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSONObject;
import com.eascs.admin.classify.entity.O2oLoanAbjustTypeFlow;
import com.eascs.admin.classify.service.O2oClassifySerivce;
import com.eascs.admin.common.exception.RunException;
import com.eascs.admin.common.service.BaseSevice;
import com.eascs.admin.common.vo.O2oUpdateLoanExpireTimeEntity;
import com.eascs.admin.item.entity.O2oPubDditemEntity;
import com.eascs.admin.item.service.O2oPubDdItemService;
import com.eascs.admin.o2o.applyAssessment.dao.ApplyAssessmentDao;
import com.eascs.admin.o2o.back.entity.O2oBackEntity;
import com.eascs.admin.o2o.back.service.O2oBackService;
import com.eascs.admin.o2o.backfee.entity.O2OComBackFee;
import com.eascs.admin.o2o.backfee.service.O2OComBankFeeService;
import com.eascs.admin.o2o.badloan.entity.O2oBadRecordEntity;
import com.eascs.admin.o2o.badloan.service.O2oBadLoanService;
import com.eascs.admin.o2o.creditarchive.service.CreditArchiveService;
import com.eascs.admin.o2o.enterpriseZX.entity.O2oEnterpriseZxEntity;
import com.eascs.admin.o2o.enterpriseZX.service.O2oEnterpriseZxService;
import com.eascs.admin.o2o.finance.entity.O2oFinanceFlowEntity;
import com.eascs.admin.o2o.finance.service.O2oFinanceFlowService;
import com.eascs.admin.o2o.generation.entity.O2oGenerationEntity;
import com.eascs.admin.o2o.generation.service.O2oGenerationService;
import com.eascs.admin.o2o.internal.controller.PayMentController;
import com.eascs.admin.o2o.internal.dao.WfTypeStatusDao;
import com.eascs.admin.o2o.internal.entity.LoanapplyExpand;
import com.eascs.admin.o2o.internal.entity.LoanapplyExpandDetail;
import com.eascs.admin.o2o.internal.entity.WfTypeStatus;
import com.eascs.admin.o2o.internal.form.PayMentForm;
import com.eascs.admin.o2o.internal.service.LoanapplyExpandDetailService;
import com.eascs.admin.o2o.internal.service.LoanapplyExpandService;
import com.eascs.admin.o2o.internal.util.BaseUserUtil;
import com.eascs.admin.o2o.internal.util.StatusContexts;
import com.eascs.admin.o2o.loan.entity.*;
import com.eascs.admin.o2o.notify.dao.WFStatusDao;
import com.eascs.admin.o2o.notify.entity.WFStatus;
import com.eascs.admin.o2o.o2ozx.serviceimpl.O2oLoadUserZxServiceImpl;
import com.eascs.admin.o2o.o2ozx.serviceimpl.O2oZxServiceImpl;
import com.eascs.admin.o2o.settle.entity.O2oSettleEntity;
import com.eascs.admin.o2o.settle.service.O2oSettleService;
import com.eascs.admin.o2o.settle.vo.O2oSettleVo;
import com.eascs.admin.o2o.specialInterview.entity.O2OSpecialInterview;
import com.eascs.admin.o2o.specialInterview.service.O2OSpecialInterviewService;
import com.eascs.admin.o2o.submitted.entity.O2oLoanSubmittedEntity;
import com.eascs.admin.o2o.submitted.serviceimpl.O2oLoanSubmittedServiceImple;
import com.eascs.admin.o2o.zx.entity.O2oLoanUserEntityZx;
import com.eascs.admin.o2o.zx.entity.O2oZxEntity;
import com.eascs.afterloan.entity.AdvancedPayment;
import com.eascs.afterloan.service.AdvanceSettleService;
import com.eascs.afterloan.service.BankCardService;
import com.eascs.afterloancheck.dao.LoanCheckDao;
import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.archive.dao.ArchiveRecordDao;
import com.eascs.archive.entity.*;
import com.eascs.archive.service.ArchiveService;
import com.eascs.archive.service.impl.ArchiveBorrowServiceImpl;
import com.eascs.archive.untils.ArchiveConstants;
import com.eascs.brand.dao.O2oBrandDao;
import com.eascs.brand.dao.O2oPartnerDao;
import com.eascs.brand.entity.O2oPartnerEntity;
import com.eascs.common.util.DateUtils;
import com.eascs.common.util.StringUtil;
import com.eascs.common.util.UuidUtil;
import com.eascs.crm.common.entity.Acq;
import com.eascs.crm.common.service.AcqService;
import com.eascs.demand.entity.MainApply;
import com.eascs.demand.service.TicketMainApplyService;
import com.eascs.deploy.dao.DeployFileDao;
import com.eascs.deploy.entity.O2oDeployFileLink;
import com.eascs.message.service.impl.O2oMessageServiceImpl;
import com.eascs.notify.mail.MailNotifier;
import com.eascs.notify.mail.MailNotifyRequest;
import com.eascs.notify.mail.MailSendType;
import com.eascs.notify.sms.SmsNotifier;
import com.eascs.notify.sms.SmsNotifyRequest;
import com.eascs.notify.sms.SmsNotifyResponse;
import com.eascs.notify.sms.SmsSendType;
import com.eascs.partner.dao.JxsPartnerDao;
import com.eascs.partner.dao.PartnerDao;
import com.eascs.partner.entity.DealerPartnerEntity;
import com.eascs.pay.entity.O2oPayEntity;
import com.eascs.pay.service.impl.O2oPayServiceImpl;
import com.eascs.paymentdetail.entity.O2oPaymentDetailEntity;
import com.eascs.paymentdetail.entity.O2oTransferAccount;
import com.eascs.paymentdetail.service.O2oPaymentDetailService;
import com.eascs.paymentdetail.service.O2oTransferAccountService;
import com.eascs.site.view.BaseRestResult;
import com.eascs.web.sso.User;
import com.eascs.web.sso.UserHolder;
import com.eascs.workflow.common.entity.wf.ProcessTaskMain;
import com.eascs.workflow.common.entity.wf.ProcessTemplate;
import com.eascs.workflow.common.service.sys.EmployeeService;
import com.eascs.workflow.common.service.sys.SysPermissionService;
import com.eascs.workflow.common.service.wf.WorkFlowService;
import com.eascs.workflow.common.vo.ModelResult;
import com.eascs.workflow.common.vo.WFNotifyParam;
import com.eascs.workflow.common.vo.WFRequestParam;
import freemarker.cache.ClassTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.inject.Inject;
import java.io.StringWriter;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;

/**
 * 工作流通知接口
 * 
 * @author user
 *
 */
@Service
public class O2OWorkFlowService extends BaseSevice {
	private static Logger log = LoggerFactory.getLogger(O2OWorkFlowService.class);
	@Inject
	TicketMainApplyService ticketMainApplyService;
	@Autowired
	BaseUserUtil baseUserUtil;
	@Autowired
	private WFStatusDao wfStatusDao;
	@Autowired
	private O2oLoanapplyService o2oLoanapplyService;
	@Autowired
	private O2oLoanUserService o2oLoanUserService;
	@Autowired
	private LoanapplyExpandService loanapplyExpandService;
	@Autowired
	private O2OComBankFeeService o2OComBankFeeService;

	@Autowired
	private O2oMessageServiceImpl o2oMessageServiceImpl;

	@Autowired
	private O2oPayServiceImpl o2oPayServiceImpl;

	@Autowired
	private O2oFinanceFlowService financeFlowService;

	@Autowired
	private O2oPaymentDetailService o2oPaymentDetailService;

	@Autowired
	private PayMentController payMentController;

	@Autowired
	private O2oBadLoanService service;

	@Autowired
	private WfTypeStatusDao wfTypeStatusDao;

	@Autowired
	O2oPartnerDao o2oPartnerDao;
	
	@Autowired
	JxsPartnerDao jxsPartnerDao;
	@Autowired
	PartnerDao partnerDao;
	@Reference
	AcqService acqService;
	
	@Autowired
	O2oBrandDao o2oBrandDao;
	
	@Autowired
	ApplyAssessmentDao applyDao;
	@Autowired
	AdvanceSettleService advanceSettleService;

	@Autowired
	LoanCheckDao loanCheckDao;
	@Autowired
	BankCardService bankCardService;

	@Autowired
	O2OSpecialInterviewService o2OSpecialInterviewService;

	@Autowired
	private LoanapplyExpandDetailService loanapplyExpandDetailService;
	@Reference
	SysPermissionService sysPermissionService;
	@Reference
	private MailNotifier mailNotifier;
	@Autowired
	private CreditArchiveService creditArchiveService;
	@Autowired
	private ArchiveBorrowServiceImpl archiveBorrowService;
	@Autowired
	private O2oPubDdItemService o2oPubDdItemService;
	@Autowired
	O2oGenerationService generationService;
	@Autowired
	O2oTransferAccountService o2oTransferAccountService;
	@Autowired
	private ArchiveRecordDao archiveRecordDao;
	@Autowired
	private ArchiveService archiveService;
	@Autowired
	DeployFileDao deployFileDao;
	
	@Autowired
	O2oZxServiceImpl o2oZxServiceImpl;
	@Autowired
	O2oClassifySerivce o2oClassifySerivce;
	@Autowired
	O2oLoadUserZxServiceImpl o2oLoadUserZxServiceImpl;
	
	@Autowired
	O2oEnterpriseZxService o2oEnterpriseZxService;
	
	@Value("${o2o.admin.wf.zxUrl}")
	private String zxUrl;
	
	@Value("${o2o.admin.wf.cwshUrl}")
	private String cwshUrl;//财务审核详情页url
	@Reference
	private WorkFlowService workFlowService;
	
	@Reference
	EmployeeService employeeService;
	
	@Reference
	private SmsNotifier smsNotifier;
	
	
	
	public ModelResult<Boolean> wfNotify(WFNotifyParam notifyParam) {
		log.info("接受来自工作的消息通知:WFNotifyParam[{}]", notifyParam.toString());
		if(UserHolder.getUser()!=null){
			log.info("UserHolder 不为空======================");
		}else{
			log.info("UserHolder-=--------空======================");
		}
		try {
			if (notifyParam.getSystemModule().equals(ProcessTemplate.SYSTEM_MODULE_O2O)) {
				
				// 节点处理方法 -- 新加的流程通知 请写在这个方法下面
				O2oLoanapplyEntity loanapplyEntity = o2oLoanapplyService.findById(notifyParam.getReferId());
				
				// 插入流程明细表
				insertWfStatus(notifyParam);
				
				String wfType = getWfType(notifyParam);
				
				// 修改流程主状态表
				WfTypeStatus wfTypeStatus = wfTypeStatusDao.getByLoanapplyNoAndWfType(notifyParam.getReferId(), wfType);
				
				if(notifyParam.getProcessStatus() == ProcessTaskMain.PROECESS_STATUS_HANDING ){ //第一次流程调用，处理中的新增,其他过程中不做处理
					if(wfTypeStatus==null){
						updateWftypeStatus(wfTypeStatus, notifyParam, wfType);
					}
				}else{
					updateWftypeStatus(wfTypeStatus, notifyParam, wfType);
				}
				
				/**
				 * 流程处理中执行start
				 */
				if (notifyParam.getProcessStatus() == ProcessTaskMain.PROECESS_STATUS_HANDING) {
					if (notifyParam.getProcessType().equals(ProcessTemplate.PROECESS_TYPE_BANK_REPORT) || notifyParam.getProcessType().equals(ProcessTemplate.PROECESS_TYPE_BANK_REPORT_FQ) || notifyParam.getProcessType().equals("CREDIT_INQUIRY")) {// 如果是处理中
//						log.info("billCode:[{}],处理节点开始：", loanapplyEntity.getBillCode());
						log.info("没有用MQ处理节点开始：");
						return dealNodecode(notifyParam, loanapplyEntity);
					} else {
						return new ModelResult<Boolean>().withModel(Boolean.TRUE);
					}
				}
				/**
				 * 流程处理中执行end
				 */
				/**
				 * 流程结束执行start
				 */
				
				if (notifyParam.getProcessType().equals(ProcessTemplate.PROECESS_TYPE_BORROW_ARCHIVE)) {
					// 归档借阅消息通知
					return notifyGDBorrow(notifyParam);
				}

				if (notifyParam.getProcessType().equals(ProcessTemplate.PROECESS_TYPE_BC_ARCHIVE)) {
					// 补充归档消息通知
					return notifyGDBC(notifyParam);
				}

				// 特殊面签申报
				if (notifyParam.getProcessType().equals(ProcessTemplate.PROECESS_TYPE_SPEC_BANK_REPORT)) {
					log.info("开始合作方申请流程通知:processId:[{}],processName:[{}],processStatus:[{}],referId:[{}]", notifyParam.getProcessId(), notifyParam.getProcessName(), notifyParam.getProcessStatus(), notifyParam.getReferId());
					updateSpecialInterview(notifyParam);
					log.info("结束合作方申请流程通知:processId:[{}],processName:[{}],processStatus:[{}],referId:[{}]", notifyParam.getProcessId(), notifyParam.getProcessName(), notifyParam.getProcessStatus(), notifyParam.getReferId());
					return new ModelResult<Boolean>().withModel(Boolean.TRUE);
				}

				// 贷后定期检查
				if (notifyParam.getProcessType().equals(ProcessTemplate.PROECESS_TYPE_REGULAR_CHECK_LOAN_AFTER)) {
					log.info("开始合作方申请流程通知:processId:[{}],processName:[{}],processStatus:[{}],referId:[{}]", notifyParam.getProcessId(), notifyParam.getProcessName(), notifyParam.getProcessStatus(), notifyParam.getReferId());
					loanCheckDao.updateRevisitWfStatus(notifyParam.getReferId(), notifyParam.getProcessStatus());
					log.info("结束合作方申请流程通知:processId:[{}],processName:[{}],processStatus:[{}],referId:[{}]", notifyParam.getProcessId(), notifyParam.getProcessName(), notifyParam.getProcessStatus(), notifyParam.getReferId());
					return new ModelResult<Boolean>().withModel(Boolean.TRUE);
				}

				// 新增合作方申请流程
				if (notifyParam.getProcessType().equals(ProcessTemplate.PROECESS_TYPE_PARTNERS_AUDIT_BP)) {
					log.info("开始合作方申请流程通知:processId:[{}],processName:[{}],processStatus:[{}],referId:[{}]", notifyParam.getProcessId(), notifyParam.getProcessName(), notifyParam.getProcessStatus(), notifyParam.getReferId());
					o2oPartnerDao.updatePartnerWfStatus(notifyParam.getReferId(), notifyParam.getProcessStatus());
					//审核通过
					if(notifyParam.getProcessStatus() == 0){
						O2oPartnerEntity o2oPartnerInfo = partnerDao.getById(O2oPartnerEntity.class, notifyParam.getReferId());
						if(o2oPartnerInfo!=null){
							Acq acq = new Acq();
							acq.setAcqCode(o2oPartnerInfo.getPartnerCode());
							acq.setProvinceCode(o2oPartnerInfo.getOrgProvinceId());
							acq.setProvinceName(o2oPartnerInfo.getOrgProvince());
							acq.setAcqName(o2oPartnerInfo.getPartnerName());
							acq.setAcqType("BP");
							acq.setAcqTypeName("流通贷-厂家");
							acq.setCreatorNo(o2oPartnerInfo.getOperatorId());
							acq.setCreatorName(o2oPartnerInfo.getOperator());
							acq.setCreateTime(new Date());
							acq.setLtdCode(o2oPartnerInfo.getOrgId());
							acq.setLtdName(o2oPartnerInfo.getOrgName());
							acq.setIsShare(o2oPartnerInfo.getIsShare());
							acqService.insertAcq(acq);
						}
					}
					log.info("结束合作方申请流程通知:processId:[{}],processName:[{}],processStatus:[{}],referId:[{}]", notifyParam.getProcessId(), notifyParam.getProcessName(), notifyParam.getProcessStatus(), notifyParam.getReferId());
					return new ModelResult<Boolean>().withModel(Boolean.TRUE);
				} else if (notifyParam.getProcessType().equals(ProcessTemplate.PROECESS_TYPE_AUDIT_BP)) {
					// 新增品牌申请流程
					log.info("开始品牌申请流程通知:processId:[{}],processName:[{}],processStatus:[{}],referId:[{}]", notifyParam.getProcessId(), notifyParam.getProcessName(), notifyParam.getProcessStatus(), notifyParam.getReferId());
					o2oBrandDao.updateBrandWfStatus(notifyParam.getReferId(), notifyParam.getProcessStatus());
					log.info("结束品牌申请流程通知:processId:[{}],processName:[{}],processStatus:[{}],referId:[{}]", notifyParam.getProcessId(), notifyParam.getProcessName(), notifyParam.getProcessStatus(), notifyParam.getReferId());
					return new ModelResult<Boolean>().withModel(Boolean.TRUE);
				}else if (notifyParam.getProcessType().equals("TQKH")) {
					// 提前进入考核期流程
					log.info("开始提前进入考核期流程通知:processId:[{}],processName:[{}],processStatus:[{}],referId:[{}]", notifyParam.getProcessId(), notifyParam.getProcessName(), notifyParam.getProcessStatus(), notifyParam.getReferId());
					applyDao.updateApplyWfStatus(notifyParam.getReferId(), notifyParam.getProcessStatus());
					log.info("结束提前进入考核期流程通知:processId:[{}],processName:[{}],processStatus:[{}],referId:[{}]", notifyParam.getProcessId(), notifyParam.getProcessName(), notifyParam.getProcessStatus(), notifyParam.getReferId());
					return new ModelResult<Boolean>().withModel(Boolean.TRUE);
				}else if(notifyParam.getProcessType().equals(ProcessTemplate.PROECESS_TYPE_JXS_PARTNERS_AUDIT_BP)){
					// 新增经销商合作方申请流程
					log.info("开始经销商合作方申请流程通知:processId:[{}],processName:[{}],processStatus:[{}],referId:[{}]", notifyParam.getProcessId(), notifyParam.getProcessName(), notifyParam.getProcessStatus(), notifyParam.getReferId());
					jxsPartnerDao.updateJxsPartnerWfStatus(notifyParam.getReferId(), notifyParam.getProcessStatus());
					//审核通过
					if(notifyParam.getProcessStatus() == 0){
						DealerPartnerEntity dealerPartnerEntity = jxsPartnerDao.getById(DealerPartnerEntity.class, notifyParam.getReferId());
						if(dealerPartnerEntity!=null){
							Acq acq = new Acq();
							acq.setAcqCode(dealerPartnerEntity.getPatternCode());
							acq.setProvinceCode(dealerPartnerEntity.getOrgProvinceId());
							acq.setProvinceName(dealerPartnerEntity.getOrgProvince());
							acq.setAcqName(dealerPartnerEntity.getBusinessLicenseName());
							acq.setAcqType("BP_JX");
							acq.setAcqTypeName("流通贷-经销商");
							acq.setCreatorNo(dealerPartnerEntity.getOperatorId());
							acq.setCreatorName(dealerPartnerEntity.getOperator());
							acq.setCreateTime(new Date());
							acq.setLtdCode(dealerPartnerEntity.getOrgId());
							acq.setLtdName(dealerPartnerEntity.getOrgName());
							acq.setIsShare(dealerPartnerEntity.getIsShare());
							acqService.insertAcq(acq);
						}
					}
					log.info("结束经销商合作方申请流程通知:processId:[{}],processName:[{}],processStatus:[{}],referId:[{}]", notifyParam.getProcessId(), notifyParam.getProcessName(), notifyParam.getProcessStatus(), notifyParam.getReferId());
					return new ModelResult<Boolean>().withModel(Boolean.TRUE);
				}else if (notifyParam.getProcessType().equals(ProcessTemplate.PROECESS_TYPE_CREDIT) || notifyParam.getProcessType().equals(ProcessTemplate.PROECESS_TYPE_CREDI_FQ) || notifyParam.getProcessType().equals(ProcessTemplate.PROECESS_TYPE_CREDI_BP)) {
					// 征信流程
					log.info("征信流程消息通知:[{}]", notifyParam.getProcessType());
					
					loanapplyEntity = zxFlow(notifyParam, loanapplyEntity);
				} else if (notifyParam.getProcessType().equals(ProcessTemplate.PROECESS_TYPE_INAUDIT) || notifyParam.getProcessType().equals(ProcessTemplate.PROECESS_TYPE_INAUDIT_FQ) || notifyParam.getProcessType().equals(ProcessTemplate.PROECESS_TYPE_INAUDIT_BP)) {
					// 内审流程
					log.info("内审流程消息通知:[{}]", notifyParam.getProcessType());
					
					loanapplyEntity = nsFlow(notifyParam, loanapplyEntity);
				} else if (notifyParam.getProcessType().equals(ProcessTemplate.PROECESS_TYPE_DEPOSIT) || notifyParam.getProcessType().equals(ProcessTemplate.PROECESS_TYPE_DEPOSIT_FQ)) {
					// 收取保证金、管理费和风险补偿金流程
					log.info("收取保证金、管理费和风险补偿金流程消息通知:[{}]", notifyParam.getProcessType());
				
					loanapplyEntity = bzjFlow(notifyParam, loanapplyEntity);
				} else if (notifyParam.getProcessType().equals(ProcessTemplate.PROECESS_TYPE_BANK_REPORT) || notifyParam.getProcessType().equals(ProcessTemplate.PROECESS_TYPE_BANK_REPORT_FQ)) {
					// 银行申报
					log.info("银行申报流程消息通知:[{}]", notifyParam.getProcessType());
					
					loanapplyEntity = sbFlow(notifyParam, loanapplyEntity);
				} else if (notifyParam.getProcessType().equals(ProcessTemplate.PROECESS_TYPE_REFUND_MGR_FEE) || notifyParam.getProcessType().equals(ProcessTemplate.PROECESS_TYPE_REFUND_MGR_FEE_FQ)) {
					// 退还保证金、管理费和风险补偿金流程
					log.info("退还保证金、管理费和风险补偿金流程消息通知:[{}]", notifyParam.getProcessType());
					
					loanapplyEntity = tfFlow(notifyParam, loanapplyEntity);
				} else if (notifyParam.getProcessType().equals(ProcessTemplate.PROECESS_TYPE_PAY_FQ)) {
					// 付费流程
					log.info("付费流程消息通知:[{}]", notifyParam.getProcessType());
					
					return payNotify(notifyParam, loanapplyEntity);
				} else if (notifyParam.getProcessType().equals(ProcessTemplate.PROECESS_TYPE_DHK)) {
					// 代还款流程
					log.info("代还款流程消息通知:[{}]", notifyParam.getProcessType());
					return generation(notifyParam, loanapplyEntity);
				} else if (notifyParam.getProcessType().equals(ProcessTemplate.PROECESS_TYPE_BACK_MONEY)) {
					// 回款流程
					log.info("回款流程消息通知:[{}]", notifyParam.getProcessType());
					
					return badLoanBack(notifyParam);
				} else if (notifyParam.getProcessType().equals(ProcessTemplate.PROECESS_TYPE_DCJQ)) {
					// 代偿结清流程
					log.info("代偿结清流程消息通知:[{}]", notifyParam.getProcessType());
				
					return settleFlow(notifyParam);
				} else if (notifyParam.getProcessType().equals(ProcessTemplate.PROECESS_TYPE_PLACE_ON_FILE) || notifyParam.getProcessType().equals(ProcessTemplate.PROECESS_TYPE_ARCHIVE)) {
					// 归档流程
					log.info("启动归档流程:[{}]", StatusContexts.WFTYPE_TYPE_PLACE_ON_FILE);
					
					loanapplyEntity = fileFlow(notifyParam, loanapplyEntity);
				} else if (notifyParam.getProcessType().equals(ProcessTemplate.PROECESS_TYPE_FINANCE_AUDIT)) {
					// 财务流程
					log.info("财务流程消息通知:[{}]", notifyParam.getProcessType());
					
					return financeFlow(notifyParam, loanapplyEntity);
				} else if (notifyParam.getProcessType().equals(ProcessTemplate.PROECESS_TYPE_TQ_PAYMENT)) {
					// 提前还款结清
					log.info("提前还款结流程消息通知:[{}]", notifyParam.getProcessType());
					
					loanapplyEntity = tqhkFlow(notifyParam, loanapplyEntity);
				} else if (notifyParam.getProcessType().equals(ProcessTemplate.PROECESS_TYPE_DC_FED_BACK)) {
					// 代偿分期流程
					log.info("代偿分期流程消息通知:[{}]", notifyParam.getProcessType());
					return backFlow(notifyParam);
				} else if (notifyParam.getProcessType().equals(ProcessTemplate.PROECESS_TYPE_CREDIT_ARCHIVE)) {
					// 征信归档
					log.info("征信归档流程消息通知:[{}]", notifyParam.getProcessType());
					zxgdFlow(notifyParam);
				} else if (notifyParam.getProcessType().equals(ProcessTemplate.PROECESS_TYPE_FKZZ)) {
					// 付款转账
					log.info("付款转账流程消息通知:[{}]", notifyParam.getProcessType());
					fkzzFlow(notifyParam);
				} else if (notifyParam.getProcessType().equals(ProcessTemplate.CASE_SUBMIT)) {
					// 案件报送流程
					log.info("案件报送流程通知:[{}]", notifyParam.getReferId());
					submitted(notifyParam);
				} else if (notifyParam.getProcessType().equals(StatusContexts.WF_TYPE_CREDIT_INQUIRY)) {
					// 新征信流程
					log.info("新征信流程通知:[{}]", notifyParam.getReferId());
					noticeNZX(notifyParam);
				}else if (notifyParam.getProcessType().equals("E_CREDIT")) {
					// 企业征信流程
					log.info("企业征信流程通知:[{}]", notifyParam.getReferId());
					noticeQYZX(notifyParam);
				}else if (notifyParam.getProcessType().equals("LOAN_TYPE")) {
					// 贷款分类流程
					log.info("贷款分类流程通知:[{}]", notifyParam.getReferId());
					return noticeClassify(notifyParam);
				} else if (notifyParam.getProcessType().equals(ProcessTemplate.PROECESS_TYPE_REQUIREMENT_APP)
						|| notifyParam.getProcessType().equals(ProcessTemplate.PROECESS_TYPE_BUS_REQUIREMENT_APP)
						|| notifyParam.getProcessType().equals(ProcessTemplate.PROECESS_TYPE_HQ_REQUIREMENT_APP)
						|| notifyParam.getProcessType().equals(ProcessTemplate.PROECESS_TYPE_SYSTEM_DEV)
						) {
					log.info("需求申请流程消息通知:[{}]", notifyParam.getProcessType());
					return financeDemand(notifyParam);
				} else {
					List<O2oPubDditemEntity> entities=o2oPubDdItemService.findPubDdItemByCodeAll("SYSDEMANDTYPE");
					for (O2oPubDditemEntity o2oPubDditemEntity : entities) {
						if (notifyParam.getProcessType().equals(o2oPubDditemEntity.getItemCode())) {
							log.info("需求申请流程消息通知:[{}]", notifyParam.getProcessType());
							return financeDemand(notifyParam);
						}
					}
					log.info("消息通知失败,ProcessType:[{}],流程类型不存在", notifyParam.getProcessType());
					return new ModelResult<>("workflow.notify.insert.error", "流程通知失败,流程类型：" + notifyParam.getProcessType() + "不存在");
				}
				
				if (loanapplyEntity != null) {// 如果是新系统的数据这个可以执行，老系统数据不行
					int effectRow = o2oLoanapplyService.updateEntityById(loanapplyEntity);
					if (effectRow <= 0) {
						log.error("billCode:[{}],更新贷款主表状态失败", loanapplyEntity.getBillCode());
						throw new RuntimeException("更新贷款主表状态失败");
					} else {
						/**
						 * 国安村镇银行的，自动启动保证金管理费流程(流程走到最后，更新了主表状态再来启动保证金管理费)
						 */
						if (notifyParam.getProcessType().equals(ProcessTemplate.PROECESS_TYPE_BANK_REPORT) || notifyParam.getProcessType().equals(ProcessTemplate.PROECESS_TYPE_BANK_REPORT_FQ)) {// 如果是国安村镇的面签申报，
							if (StatusContexts.O2O_BANKTYPE_GACZ.equals(loanapplyEntity.getBankLoanName())) {
								PayMentForm payform = new PayMentForm();
								payform.setBillCode(loanapplyEntity.getBillCode());
								payform.setLoanapplyNo(loanapplyEntity.getLoanapplyNo());
								payform.setWfType(wfType);
								BaseRestResult<String> result = payMentController.order(payform);
								log.info("启动保证金管理费流程结构,result：[{}]", result.getData());
							}
						}
					}
					log.error("billCode:[{}],更新贷款主表状态成功", loanapplyEntity.getBillCode());
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			log.error("ReferId:[{}],工作流消息异常:[{}]", notifyParam.getReferId(), e);
			return new ModelResult<>("workflow.notify.insert.error", "流程通知插入失败");
		}
		return new ModelResult<Boolean>().withModel(Boolean.TRUE);
	}

	/**
	 * 
	 * 归档流程
	 * 
	 * @param notifyParam
	 * @param loanapplyEntity
	 * @return
	 */
	private O2oLoanapplyEntity fileFlow(WFNotifyParam notifyParam, O2oLoanapplyEntity loanapplyEntity) {
		if (notifyParam.getProcessStatus() == ProcessTaskMain.PROECESS_STATUS_PASS) {
			log.info("归档流程通过记录通知：{}", loanapplyEntity.getBillCode());
			loanapplyEntity.setIsPlaceOnFile(StatusContexts.WFTYPE_STATUS_CLO);
			loanapplyEntity.setPlaceOnFileTime(new Date());
		} else if (notifyParam.getProcessStatus() == ProcessTaskMain.PROECESS_STATUS_TURNED_DOWN) {
			log.info("归档流程驳回记录通知：{}", loanapplyEntity.getBillCode());
			loanapplyEntity.setIsPlaceOnFile(StatusContexts.O2O_NEW);
		} else if (notifyParam.getProcessStatus().equals(ProcessTaskMain.PROECESS_STATUS_REJECT)) {
			log.info("归档流程作废记录通知：{}", loanapplyEntity.getBillCode());
		}
		return loanapplyEntity;
	}

	/**
	 * 财务流程
	 * 
	 * @param notifyParam
	 * @param loanapplyEntity
	 * @return
	 */
	private ModelResult<Boolean> financeFlow(WFNotifyParam notifyParam, O2oLoanapplyEntity loanapplyEntity) {
		if (notifyParam.getProcessStatus() == ProcessTaskMain.PROECESS_STATUS_PASS) {
			log.info("财务审核通过：billcode【{}】", loanapplyEntity.getBillCode());
			O2oFinanceFlowEntity entity = financeFlowService.getByLoanApplyno(notifyParam.getReferId());
			entity.setFlowStatus(StatusContexts.O2O_BANK_CLO);
			entity.setEndTime(new Date());
			int i = financeFlowService.update(entity);
			if (i > 0) {
				return new ModelResult<Boolean>().withModel(Boolean.TRUE);
			} else {
				log.info("更新O2oFinanceFlowEntity财务审核失败:[{}]", entity.getBillCode());
				return new ModelResult<>("workflow.notify.insert.error", "财务审核流程通过通知失败");
			}
		} else if (notifyParam.getProcessStatus() == ProcessTaskMain.PROECESS_STATUS_TURNED_DOWN) {
			log.info("财务审核驳回：【{}】", loanapplyEntity.getBillCode());
			O2oFinanceFlowEntity entity = financeFlowService.getByLoanApplyno(notifyParam.getReferId());
			entity.setFlowStatus(StatusContexts.O2O_BANK_NEW);
			int i = financeFlowService.update(entity);
			if (i > 0) {
				return new ModelResult<Boolean>().withModel(Boolean.TRUE);
			} else {
				log.info("更新O2oFinanceFlowEntity财务审核失败:[{}]", entity.getBillCode());
				return new ModelResult<>("workflow.notify.insert.error", "财务审核流程驳回通知失败");
			}
		} else if (notifyParam.getProcessStatus().equals(ProcessTaskMain.PROECESS_STATUS_REJECT)) {

		}
		return new ModelResult<Boolean>().withModel(Boolean.TRUE);
	}

	/**
	 * 
	 * 退费流程
	 * 
	 * @param notifyParam
	 * @return
	 */
	private O2oLoanapplyEntity tfFlow(WFNotifyParam notifyParam, O2oLoanapplyEntity loanapply) {
		if (notifyParam.getProcessStatus() == ProcessTaskMain.PROECESS_STATUS_PASS) {
			log.info("退费流程通过：ReferId:[{}]", notifyParam.getReferId());
			O2OComBackFee o2OComBackFee = o2OComBankFeeService.queryEntity(notifyParam.getReferId(), StatusContexts.BZJ_STATUS_RUN);
			// 2；修改 O2OComBackFee 中的状态
			o2OComBackFee.setBillStatus(StatusContexts.WFTYPE_STATUS_CLO);
			/*
			 * if (StatusContexts.DATA_SOURCE_OLD.equals(o2OComBackFee.
			 * getDataSource())) { // 如果是老系统则修改老系统中保证金管理费的值 OaBackFeeEntity
			 * oaBackFeeEntity =
			 * o2OComBankFeeService.findOaBackFee(o2OComBackFee.getBillCode());
			 * LoanapplyExpand loanapplyExpand =
			 * OaBackFeeTransO2Oloanapply.transloanapplyExpand(oaBackFeeEntity);
			 * loanapplyExpand = insertPaymentDetail(loanapplyExpand,
			 * o2OComBackFee); // 插入明细表,处理剩余的要修改库的数据 int updateresult =
			 * o2OComBankFeeService.updateBackFee(loanapplyExpand); if
			 * (updateresult > 0) { log.info("老系统ReferId:[{}],更新老系统主表数据成功",
			 * notifyParam.getReferId()); } else {
			 * log.info("老系统ReferId:[{}],更新老系统主表数据失败",
			 * notifyParam.getReferId()); } int i =
			 * o2OComBankFeeService.updateById(o2OComBackFee); if (i > 0) {
			 * log.info("老系统ReferId:[{}],更新退费表状态成功", notifyParam.getReferId());
			 * } else { log.info("老系统ReferId:[{}],更新退费表状态失败",
			 * notifyParam.getReferId()); } } else {
			 */
			LoanapplyExpand loanapplyExpand = new LoanapplyExpand();
			// 1：更新loanapplyExpand中已退未退金额
			loanapplyExpand = loanapplyExpandService.queryLoanapplyNo(notifyParam.getReferId());
			// 已退金额 = 以前已退金额 + 已退(本次退费金额)
			loanapplyExpand = insertPaymentDetail(loanapplyExpand, o2OComBackFee);//// 插入明细表
			if (loanapplyExpand.getRedManger().compareTo(loanapplyExpand.getRetaManage()) <= 0 && loanapplyExpand.getRedRisk().compareTo(loanapplyExpand.getRetaRisk()) <= 0 && loanapplyExpand.getRedDeposite().compareTo(loanapplyExpand.getRetaDeposite()) <= 0) { // 如果已经已还金额>=应还
				loanapplyExpand.setIsBackOver(StatusContexts.O2O_YES);
			}
			loanapplyExpandService.updateById(loanapplyExpand); // 修改expand表中的数据
			int i = o2OComBankFeeService.updateById(o2OComBackFee);
			if (i > 0) {
				log.info("ReferId:[{}],更新退费表状态成功", notifyParam.getReferId());
			} else {
				log.info("ReferId:[{}],更新退费表状态失败", notifyParam.getReferId());
			}
			// }
		} else if (notifyParam.getProcessStatus() == ProcessTaskMain.PROECESS_STATUS_TURNED_DOWN) {
			log.info("退费流程驳回：ReferId:[{}]", notifyParam.getReferId());
			O2OComBackFee o2OComBackFee = o2OComBankFeeService.queryEntity(notifyParam.getReferId(), StatusContexts.BZJ_STATUS_RUN);
			o2OComBackFee.setBillStatus(StatusContexts.BZJ_STATUS_NEW);
			int i = o2OComBankFeeService.updateById(o2OComBackFee);
			if (i > 0) {
				log.info("ReferId:[{}],驳回退保证金管理费成功", notifyParam.getReferId());
			} else {
				log.info("ReferId:[{}],驳回退保证金管理费失败", notifyParam.getReferId());
			}
		} else if (notifyParam.getProcessStatus().equals(ProcessTaskMain.PROECESS_STATUS_REJECT)) {
			log.info("退费流程作废：ReferId:[{}]", notifyParam.getReferId());

		}
		return loanapply;
	}

	/**
	 * @Title: tqhkFlow
	 * @Description: 提前还款结清流程
	 * @author 张庆奇
	 * @param notifyParam
	 * @param loanapply
	 * @return
	 * @return O2oLoanapplyEntity
	 * @throws @date
	 *             2017年2月20日 下午3:09:10
	 */
	private O2oLoanapplyEntity tqhkFlow(WFNotifyParam notifyParam, O2oLoanapplyEntity loanapply) {
		if (notifyParam.getProcessStatus() == ProcessTaskMain.PROECESS_STATUS_PASS) {
			log.info("提前还款结清流程通过：ReferId:[{}]", notifyParam.getReferId());
			AdvancedPayment advancedPayment = advanceSettleService.queryEntity(notifyParam.getReferId(), StatusContexts.BZJ_STATUS_RUN);
			// 1 修改提前还款结清表数据状态
			advancedPayment.setBillStatus(StatusContexts.WFTYPE_STATUS_CLO);
			advancedPayment.setUpdateTime(new Date());
			int i = advanceSettleService.updateById(advancedPayment);
			if (i > 0) {
				log.info("ReferId:[{}],更新提前还款流程表状态成功", notifyParam.getReferId());
			} else {
				log.info("eferId:[{}],更新提前还款流程表状态失败", notifyParam.getReferId());
			}

			// 2.赋值
			loanapply.setSettleDate(advancedPayment.getSettleDate());
			loanapply.setWfType(StatusContexts.O2O_REPAY_END);

		} else if (notifyParam.getProcessStatus() == ProcessTaskMain.PROECESS_STATUS_TURNED_DOWN) {
			log.info("驳回提前还款结清：ReferId:[{}]", notifyParam.getReferId());
			AdvancedPayment advancedPayment = advanceSettleService.queryEntity(notifyParam.getReferId(), StatusContexts.BZJ_STATUS_RUN);
			advancedPayment.setBillStatus(StatusContexts.WFTYPE_STATUS_NEW);
			advancedPayment.setUpdateTime(new Date());
			int i = advanceSettleService.updateById(advancedPayment);
			if (i > 0) {
				log.info("ReferId:[{}],更新提前还款流程表状态成功", notifyParam.getReferId());
			} else {
				log.info("eferId:[{}],更新提前还款流程表状态失败", notifyParam.getReferId());
			}
		}
		return loanapply;
	}

	/**
	 * @Title: fkzzFlow
	 * @Description: 付款转账
	 * @author 张庆奇
	 * @param notifyParam
	 * @return
	 * @return O2oLoanapplyEntity
	 * @throws @date
	 *             2017年5月19日 上午11:38:16
	 */
	private void fkzzFlow(WFNotifyParam notifyParam) {
		O2oTransferAccount entity = o2oTransferAccountService.findById(notifyParam.getReferId());
		if (notifyParam.getProcessStatus() == ProcessTaskMain.PROECESS_STATUS_PASS) {
			log.info("付款转账流程通过：ReferId:[{}]", notifyParam.getReferId());

			// 1 修改付款转账表数据状态
			entity.setBillStatus(StatusContexts.WFTYPE_STATUS_CLO);
			entity.setUpdateTime(new Date());
			int i = o2oTransferAccountService.updateEntityById(entity);
			if (i > 0) {
				log.info("ReferId:[{}],更新付款转账流程表状态成功", notifyParam.getReferId());
			} else {
				log.info("eferId:[{}],更新付款转账流程表状态失败", notifyParam.getReferId());
			}

		} else if (notifyParam.getProcessStatus() == ProcessTaskMain.PROECESS_STATUS_TURNED_DOWN) {
			log.info("驳回付款转账：ReferId:[{}]", notifyParam.getReferId());
			entity.setBillStatus(StatusContexts.WFTYPE_STATUS_BH);
			entity.setUpdateTime(new Date());
			int i = o2oTransferAccountService.updateEntityById(entity);
			if (i > 0) {
				log.info("ReferId:[{}],更新付款转账流程表状态成功", notifyParam.getReferId());
			} else {
				log.info("eferId:[{}],更新付款转账流程表状态失败", notifyParam.getReferId());
			}
		}

	}

	/**
	 * 申报流程
	 * 
	 * @param notifyParam
	 * @param loanapplyEntity
	 * @return
	 */
	private O2oLoanapplyEntity sbFlow(WFNotifyParam notifyParam, O2oLoanapplyEntity loanapplyEntity) {
		if (notifyParam.getProcessStatus() == ProcessTaskMain.PROECESS_STATUS_PASS) {
			/*
			 * String bank_type = loanapplyEntity.getBankLoanName(); //放款银行
			 * if(StatusContexts.O2O_BANKTYPE_BC.equals(bank_type)||
			 * StatusContexts.O2O_BANKTYPE_CCBHN.equals(bank_type)
			 * ||StatusContexts.O2O_BANKTYPE_CBC.equals(bank_type) ||
			 * StatusContexts.O2O_BANKTYPE_GACZ.equals(bank_type)){
			 * try{//面签申报完成之后发送短信 ModelResult<Boolean> messageResult =
			 * o2oMessageServiceImpl.mqsbMessage(loanapplyEntity.getBillCode());
			 * if(messageResult.getModel()){ //如果是返回的是true，说明是成功的 log.info(
			 * "billCode:[{}],面签申报 银行申报审查节点通过后给客户 发送通知短信成功"
			 * ,loanapplyEntity.getBillCode()); }else{ log.error(
			 * "billCode:[{}],面签申报 银行申报审查节点通过后给客户 发送通知短信失败"
			 * ,loanapplyEntity.getBillCode()); } }catch(Exception e){
			 * log.error("billCode:[{}],面签申报 银行申报审查节点通过后给客户 发送通知短信失败："
			 * ,loanapplyEntity.getBillCode()); } }
			 */
			log.info("贷款编号:[{}],申报流程完成,修改为主表状态为：[{}]", loanapplyEntity.getBillCode(), StatusContexts.O2O_FK_END);
			loanapplyEntity.setWfType(StatusContexts.O2O_FK_END);
		} else if (notifyParam.getProcessStatus() == ProcessTaskMain.PROECESS_STATUS_TURNED_DOWN) {
			log.info("贷款编号:[{}],申报流程驳回,修改为主表状态为：[{}]", loanapplyEntity.getBillCode(), StatusContexts.O2O_NS_END);
			loanapplyEntity.setWfType(StatusContexts.O2O_NS_END);
		} else if (notifyParam.getProcessStatus().equals(ProcessTaskMain.PROECESS_STATUS_REJECT)) {
			log.info("贷款编号:[{}],申报流程作废,修改为主表状态为：[{}]", loanapplyEntity.getBillCode(), StatusContexts.O2O_FK_OVER);
			loanapplyEntity.setWfType(StatusContexts.O2O_FK_OVER);
		}
		return loanapplyEntity;
	}

	/**
	 * 保证金流程
	 * 
	 * @param notifyParam
	 * @param loanapplyEntity
	 */
	private O2oLoanapplyEntity bzjFlow(WFNotifyParam notifyParam, O2oLoanapplyEntity loanapplyEntity) {
		LoanapplyExpand loanapplyExpand = loanapplyExpandService.queryLoanapplyNo(loanapplyEntity.getLoanapplyNo());
		if (notifyParam.getProcessStatus() == ProcessTaskMain.PROECESS_STATUS_PASS) {// 流程通过
			loanapplyExpand.setBillStatus(StatusContexts.BZJ_STATUS_CLO);
			loanapplyExpand.setLoanapply_no(notifyParam.getReferId());
			int i = loanapplyExpandService.updateWorkFlow(loanapplyExpand);
			if (i <= 0) {
				log.info("贷款编号:[{}],保证金流程完成,修改失败", loanapplyEntity.getBillCode());
				throw new RuntimeException();
			}
			log.info("贷款编号:[{}],保证金流程完成,修改状态为：[{}]", loanapplyEntity.getBillCode(), StatusContexts.BZJ_STATUS_CLO);
		} else if (notifyParam.getProcessStatus() == ProcessTaskMain.PROECESS_STATUS_TURNED_DOWN) {// 流程驳回
			loanapplyExpand.setBillStatus(StatusContexts.BZJ_STATUS_NEW);
			loanapplyExpand.setLoanapply_no(notifyParam.getReferId());
			int a = loanapplyExpandService.updateWorkFlow(loanapplyExpand);
			if (a <= 0) {
				log.info("贷款编号:[{}],保证金流程驳回,修改LoanapplyExpand表失败", loanapplyEntity.getBillCode());
				throw new RuntimeException();
			}
			log.info("贷款编号:[{}],保证金流程驳回,修改LoanapplyExpand表状态为：[{}]", loanapplyEntity.getBillCode(), StatusContexts.BZJ_STATUS_CLO);
		} else if (notifyParam.getProcessStatus().equals(ProcessTaskMain.PROECESS_STATUS_REJECT)) {// 作废
			log.info("贷款编号:[{}],内审流程作废,修改为主表状态为：[{}]", loanapplyEntity.getBillCode(), StatusContexts.O2O_FK_OVER);
			loanapplyEntity.setWfType(StatusContexts.O2O_FK_OVER);
		}
		/******************* 通过或者驳回,删除保证金中间表数据 ***********************/
		LoanapplyExpandDetail loanapplyExpandDetail = loanapplyExpandDetailService.queryDetail(loanapplyExpand.getId());
		if (loanapplyExpandDetail != null) {
			loanapplyExpandDetailService.delete(loanapplyExpandDetail.getId());
			log.info("保证金通过删除中间表数据,贷款单号：[{}],id[{}]", loanapplyExpandDetail.getBillCode(), loanapplyExpandDetail.getId());
		}
		return loanapplyEntity;
	}

	/**
	 * 内审流程
	 * 
	 * @param notifyParam
	 * @param loanapplyEntity
	 * @return
	 */
	private O2oLoanapplyEntity nsFlow(WFNotifyParam notifyParam, O2oLoanapplyEntity loanapplyEntity) {
		if (notifyParam.getProcessStatus() == ProcessTaskMain.PROECESS_STATUS_PASS) {// 流程通过
			log.info("贷款编号:[{}],内审流程完成,修改为主表状态为：[{}]", loanapplyEntity.getBillCode(), StatusContexts.O2O_ZX_END);
			loanapplyEntity.setWfType(StatusContexts.O2O_NS_END);
			try {
				ModelResult<Boolean> messageResult = o2oMessageServiceImpl.nsEndMessage(loanapplyEntity.getBillCode());
				if (messageResult.getModel()) { // 如果是返回的是true，说明是成功的
					log.info("billCode:[{}],内审完成给经办人,客户发送短信成功", loanapplyEntity.getBillCode());
				} else {
					log.error("billCode:[{}],内审完成给经办人,客户发送短信失败", loanapplyEntity.getBillCode());
				}
			} catch (Exception e) {
				log.error("billCode:[{}],内审完成发送短信失败：", loanapplyEntity.getBillCode());
			}
			if (loanapplyEntity.getLoanType().equals(StatusContexts.LOAN_TYPE_EA) || loanapplyEntity.getLoanType().equals(StatusContexts.LOAN_TYPE_FQ)) {
				try {
					loanapplyEntity.setRepaymentSource(StatusContexts.DATA_SOURCE_NEW);
					int i = o2oPayServiceImpl.insertPayByEntity(loanapplyEntity, StatusContexts.PAY_TYPE_ZD, null);
					if (i > 0) {
						log.info("内审完成插入付款流程数据成功，贷款单号为：{}", notifyParam.getReferId());
						O2oLoanUserEntity loanUserEntity = o2oLoanapplyService.findLoanUserEntity(loanapplyEntity.getLoanapplyNo(), loanapplyEntity.getLoanId());
						ModelResult<Boolean> model = o2oPayServiceImpl.startPayFlow(loanapplyEntity, loanUserEntity.getUserFullName());
						if (model.isSuccess()) {
							log.info("内审完成启动付款流程数据成功，贷款单号为：{}", notifyParam.getReferId());
							O2oPayEntity o2oPayEntity = o2oPayServiceImpl.findEntityByLoanapplyId(loanapplyEntity.getLoanapplyNo());
							if (null != o2oPayEntity) {
								o2oPayEntity.setSubmitTime(new Date());
								o2oPayEntity.setSubmitUser(loanapplyEntity.getOperatorNo());
								o2oPayEntity.setBillStatus(StatusContexts.O2O_BANK_RUN);
								o2oPayEntity.setLastUpdateTime(new Date());
								int flag = o2oPayServiceImpl.updateEntityById(o2oPayEntity);
								if (flag <= 0) {
									log.info("内审完成启动付款流程数据成功，贷款单号为：{},更新付款数据失败", notifyParam.getReferId());
									throw new RunException("贷款单号：" + loanapplyEntity.getBillCode() + "分期贷和接力贷自动启动付款流程,更新付款数据失败");
								}
								log.info("内审完成启动付款流程数据成功，贷款单号为：{},更新付款数据成功", notifyParam.getReferId());
							}
						} else {
							log.error("内审完成启动付款流程数据成功，贷款单号为：{},失败原因：{}", notifyParam.getReferId(), model.getDetailStack());
						}
					}
				} catch (Exception e) {
					log.error("内审完成插入启动付款流程数据失败,贷款单号为：{},失败原因：{}", notifyParam.getReferId(), e.getMessage());
				}
			}
		} else if (notifyParam.getProcessStatus() == ProcessTaskMain.PROECESS_STATUS_TURNED_DOWN) {// 流程驳回
			log.info("贷款编号:[{}],内审流程驳回,修改为主表状态为：[{}]", loanapplyEntity.getBillCode(), StatusContexts.O2O_NEW);
			loanapplyEntity.setWfType(StatusContexts.O2O_ZX_END);
		} else if (notifyParam.getProcessStatus().equals(ProcessTaskMain.PROECESS_STATUS_REJECT)) {// 作废
			log.info("贷款编号:[{}],内审流程作废,修改为主表状态为：[{}]", loanapplyEntity.getBillCode(), StatusContexts.O2O_FK_OVER);
			loanapplyEntity.setWfType(StatusContexts.O2O_FK_OVER);
		}
		return loanapplyEntity;
	}

	/**
	 * 征信流程
	 * 
	 * @param notifyParam
	 * @param loanapplyEntity
	 * @return
	 */
	private O2oLoanapplyEntity zxFlow(WFNotifyParam notifyParam, O2oLoanapplyEntity loanapplyEntity) {
		if (notifyParam.getProcessStatus() == ProcessTaskMain.PROECESS_STATUS_PASS) {// 流程通过
			log.info("贷款编号:[{}],征信流程完成,修改为主表状态为：[{}]", loanapplyEntity.getBillCode(), StatusContexts.O2O_ZX_END);
			loanapplyEntity.setWfType(StatusContexts.O2O_ZX_END);
			// 分期贷和接力贷银行,强制修改为EA
			if (loanapplyEntity.getLoanType().equals(StatusContexts.LOAN_TYPE_EA) || loanapplyEntity.getLoanType().equals(StatusContexts.LOAN_TYPE_FQ)) {
				loanapplyEntity.setBankType("EA");
			}
		} else if (notifyParam.getProcessStatus() == ProcessTaskMain.PROECESS_STATUS_TURNED_DOWN) {// 流程驳回
			log.info("贷款编号:[{}],征信流程驳回,修改为主表状态为：[{}]", loanapplyEntity.getBillCode(), StatusContexts.O2O_NEW);
			loanapplyEntity.setWfType(StatusContexts.O2O_NEW);
		} else if (notifyParam.getProcessStatus().equals(ProcessTaskMain.PROECESS_STATUS_REJECT)) {// 作废
			log.info("贷款编号:[{}],征信流程作废,修改为主表状态为：[{}]", loanapplyEntity.getBillCode(), StatusContexts.O2O_FK_OVER);
			loanapplyEntity.setWfType(StatusContexts.O2O_FK_OVER);
		}
		return loanapplyEntity;
	}

	/**
	 * 插入流程主状态
	 * 
	 * @param wfTypeStatus
	 * @param notifyParam
	 * 
	 */
	@Transactional("o2oTransactionManager")
	private void updateWftypeStatus(WfTypeStatus wfTypeStatus, WFNotifyParam notifyParam, String wfType) {
		if (wfTypeStatus == null) {
			log.info("ReferId:[{}],插入流程主状态数据", notifyParam.getReferId());
			WfTypeStatus wfTypeStatus_ = new WfTypeStatus();
			wfTypeStatus_.setLoapplyNo(notifyParam.getReferId());
			wfTypeStatus_.setWfType(wfType);
			wfTypeStatus_.setWfDate(notifyParam.getLastUpdateTime());
			if (notifyParam.getProcessStatus() == ProcessTaskMain.PROECESS_STATUS_PASS) {// 处理完成
				wfTypeStatus_.setWfStatus(StatusContexts.WFTYPE_STATUS_CLO);
			} else if (notifyParam.getProcessStatus() == ProcessTaskMain.PROECESS_STATUS_TURNED_DOWN) {// 驳回
				//20180306版本上线之后都变为驳回BH
				wfTypeStatus_.setWfStatus(StatusContexts.WFTYPE_STATUS_BH);
			} else if (notifyParam.getProcessStatus().equals(ProcessTaskMain.PROECESS_STATUS_REJECT)) {// 作废
				wfTypeStatus_.setWfStatus(StatusContexts.O2O_FK_OVER);
			} else {
				wfTypeStatus_.setWfStatus(StatusContexts.WFTYPE_STATUS_RUN);
			}
			wfTypeStatus_.setStartDate(new Date());
			int effectRow = wfTypeStatusDao.insert(wfTypeStatus_);
			if (effectRow <= 0) {
				log.info("ReferId:[{}],插入工作流状态表失败", notifyParam.getReferId());
				throw new RuntimeException("插入工作流状态表失败");
			}
			log.info("ReferId:[{}],插入工作流状态表成功", notifyParam.getReferId());
		} else {
			log.info("ReferId:[{}],更新流程主状态表数据", notifyParam.getReferId());
			if (notifyParam.getProcessStatus() == ProcessTaskMain.PROECESS_STATUS_PASS) {// 处理完成
				wfTypeStatus.setWfStatus(StatusContexts.WFTYPE_STATUS_CLO);
				wfTypeStatus.setEndDate(new Date());
			} else if (notifyParam.getProcessStatus() == ProcessTaskMain.PROECESS_STATUS_TURNED_DOWN) {// 驳回
				//20180306版本上线之后都变为驳回BH
				wfTypeStatus.setWfStatus(StatusContexts.WFTYPE_STATUS_BH);
			} else if (notifyParam.getProcessStatus().equals(ProcessTaskMain.PROECESS_STATUS_REJECT)) {// 作废
				wfTypeStatus.setWfStatus(StatusContexts.O2O_FK_OVER);
			} else {
				wfTypeStatus.setWfStatus(StatusContexts.WFTYPE_STATUS_RUN);
			}
			wfTypeStatus.setWfType(wfType);
			wfTypeStatus.setWfDate(notifyParam.getLastUpdateTime());
			int effectRow = wfTypeStatusDao.updateById(wfTypeStatus);
			if (effectRow <= 0) {
				log.info("ReferId:[{}],更新工作流状态表失败", notifyParam.getReferId());
				throw new RuntimeException("ReferId:[{}],更新工作流状态表失败" + notifyParam.getReferId());
			}
			log.info("ReferId:[{}],更新工作流状态表成功", notifyParam.getReferId());
		}
	}

	/**
	 * 插入工作流流程明细状态
	 * 
	 * @param notifyParam
	 */
	@Transactional("o2oTransactionManager")
	private void insertWfStatus(WFNotifyParam notifyParam) {
		log.info("开始插入流程明细表：ReferId[{}]", notifyParam.getReferId());
		WFStatus wfStatus = new WFStatus();
		wfStatus.setLoadId(notifyParam.getReferId());
		wfStatus.setProcessId(notifyParam.getProcessId());
		wfStatus.setProcessStatus(notifyParam.getProcessStatus());
		wfStatus.setProcessType(notifyParam.getProcessType());
		wfStatus.setCreateTime(notifyParam.getLastUpdateTime());
		wfStatus.setCreatorName(notifyParam.getProcessName());
		wfStatus.setCreatorNo(notifyParam.getAppliedby());
		wfStatus.setCreatorName(notifyParam.getAppliedbyName());
		int effectRows = wfStatusDao.insert(wfStatus);
		if (effectRows <= 0) {
			log.info("插入流程明细表失败：ReferId[{}]", notifyParam.getReferId());
			throw new RuntimeException("ReferId:" + notifyParam.getReferId() + ",插入请求的日志信息表失败");
		}
		log.info("插入流程明细表成功：ReferId[{}]", notifyParam.getReferId());
	}

	/**
	 * 退还保证金、管理费和风险补偿金,插入明细表
	 */
	public LoanapplyExpand insertPaymentDetail(LoanapplyExpand loanapplyExpand, O2OComBackFee o2OComBackFee) {
		O2oPaymentDetailEntity o2oPaymentDetailEntity = new O2oPaymentDetailEntity();
		o2oPaymentDetailEntity.setBillCode(o2OComBackFee.getBillCode());
		o2oPaymentDetailEntity.setLoanapplyNo(o2OComBackFee.getLoanapplyNo());
		o2oPaymentDetailEntity.setPaymentType(StatusContexts.PAYMENT_TYPE_F);
		o2oPaymentDetailEntity.setHappenSource("贷款单号：" + o2OComBackFee.getBillCode());
		o2oPaymentDetailEntity.setOperationNo(o2OComBackFee.getCreatorId());
		o2oPaymentDetailEntity.setOperationName(o2OComBackFee.getCreatorName());
		if (o2OComBackFee.getPayDate() == null) {
			o2oPaymentDetailEntity.setUpdateTime(new Date());
		} else {
			o2oPaymentDetailEntity.setUpdateTime(o2OComBackFee.getPayDate());
		}
		o2oPaymentDetailEntity.setRecordTime(new Date());
		// 插入明细表
		if (o2OComBackFee.getBackDeposite().compareTo(BigDecimal.ZERO) > 0) {
			o2oPaymentDetailEntity.setSubjectType(StatusContexts.SUBJECT_TYPE_BZJ);
			o2oPaymentDetailEntity.setAmountMoney(o2OComBackFee.getBackDeposite());
			o2oPaymentDetailEntity.setRemark("系统单号:" + o2OComBackFee.getBillCode() + "退保证金：" + o2OComBackFee.getBackDeposite());
			o2oPaymentDetailService.saveEntity(o2oPaymentDetailEntity);
		}
		// 插入明细表
		if (o2OComBackFee.getBackManger().compareTo(BigDecimal.ZERO) > 0) {
			o2oPaymentDetailEntity.setId(null);
			o2oPaymentDetailEntity.setSubjectType(StatusContexts.SUBJECT_TYPE_GLF);
			o2oPaymentDetailEntity.setAmountMoney(o2OComBackFee.getBackManger());
			o2oPaymentDetailEntity.setRemark("系统单号:" + o2OComBackFee.getBillCode() + "退管理费：" + o2OComBackFee.getBackManger());
			o2oPaymentDetailService.saveEntity(o2oPaymentDetailEntity);
		}
		// 插入明细表
		if (o2OComBackFee.getBackRisk().compareTo(BigDecimal.ZERO) > 0) {
			o2oPaymentDetailEntity.setId(null);
			o2oPaymentDetailEntity.setSubjectType(StatusContexts.SUBJECT_TYPE_FXBCJ);
			o2oPaymentDetailEntity.setAmountMoney(o2OComBackFee.getBackRisk());
			o2oPaymentDetailEntity.setRemark("系统单号:" + o2OComBackFee.getBillCode() + "退风险补偿金：" + o2OComBackFee.getBackRisk());
			o2oPaymentDetailService.saveEntity(o2oPaymentDetailEntity);
		}
		if (loanapplyExpand.getRetaDeposite() != null) {
			loanapplyExpand.setRetaDeposite(loanapplyExpand.getRetaDeposite().add(o2OComBackFee.getBackDeposite()));

		} else {
			loanapplyExpand.setRetaDeposite(o2OComBackFee.getBackDeposite());
		}

		if (loanapplyExpand.getRetaManage() != null) {
			loanapplyExpand.setRetaManage(loanapplyExpand.getRetaManage().add(o2OComBackFee.getBackManger()));
		} else {
			loanapplyExpand.setRetaManage(o2OComBackFee.getBackManger());
		}
		if (loanapplyExpand.getRetaRisk() != null) {
			loanapplyExpand.setRetaRisk(loanapplyExpand.getRetaRisk().add(o2OComBackFee.getBackRisk()));

		} else {
			loanapplyExpand.setRetaRisk(o2OComBackFee.getBackRisk());
		}
		return loanapplyExpand;
	}

	/**
	 * @Description:
	 * 				<p>
	 *               付费流程结束通知
	 *               </p>
	 * @author CXW
	 * @date 2016年12月5日 下午5:47:25
	 * @version V1.0
	 */
	public ModelResult<Boolean> payNotify(WFNotifyParam notifyParam, O2oLoanapplyEntity loanapplyEntity) {
		if (notifyParam.getProcessStatus() == ProcessTaskMain.PROECESS_STATUS_PASS) {
			O2oPayEntity o2oPayEntity = new O2oPayEntity();
			o2oPayEntity = o2oPayServiceImpl.findById(notifyParam.getReferId());
			log.info("付款查询：{}", o2oPayEntity);
			o2oPayEntity.setBillStatus(StatusContexts.WFTYPE_STATUS_CLO);
			if (StatusContexts.PAY_TYPE_ZD.equals(o2oPayEntity.getPayType())) {
				loanapplyEntity = o2oLoanapplyService.findById(o2oPayEntity.getLoanapplyid());
				loanapplyEntity.setPaymentTime(o2oPayEntity.getPayDate());// 修改主表付款时间
				loanapplyEntity.setWfType(StatusContexts.O2O_FK_END); // 修改主表放款状态
				loanapplyEntity.setLoanFlg(StatusContexts.O2O_YES);// 修改主表放款标识
				O2oUpdateLoanExpireTimeEntity updateLoanTime = new O2oUpdateLoanExpireTimeEntity();// 直贷增加到期日时间
				updateLoanTime.setLoanapplyNo(loanapplyEntity.getLoanapplyNo());
				updateLoanTime.setLoanTime(o2oPayEntity.getPayDate());
				String loanTerm = bankCardService.getBankTerm(loanapplyEntity.getBillCode());
				int intloanTerm = 0;
				if(StringUtil.isNotBlank(loanTerm))
				{
					intloanTerm = Integer.parseInt(loanTerm);
				}
				updateLoanTime.setTerm(intloanTerm);
				updateLoanTime.setExpireTime();
				loanapplyEntity.setEndBankDate(new java.sql.Date(updateLoanTime.getExpireTime().getTime()));
			} else {
				loanapplyEntity = o2oLoanapplyService.findById(o2oPayEntity.getLoanapplyid());
				if ("DC".equals(o2oPayEntity.getLoanType())) {// 当选择为本金代偿时修改主单状态为代偿
					loanapplyEntity.setWfType(StatusContexts.LOAN_TYPE_DC);
				}
				if ("LXDC".equals(o2oPayEntity.getLoanType())) {// 当选择为利息代偿时修改主单状态为逾期
					loanapplyEntity.setWfType("YQ");
				}
				loanapplyEntity.setSettleDate(null);
			}
			// 付款流程結束，向銀行放款数据表中插入数据
			log.info("付款流程结束，付款类型为：{}", o2oPayEntity.getPayType());
			O2oLoanUserEntity loanUser = o2oLoanUserService.findById(loanapplyEntity.getLoanId(), loanapplyEntity.getLoanapplyNo());
			O2oLoanapplyEntity loan = o2oLoanapplyService.fingByBillCode(o2oPayEntity.getBillCode());
			Date date = new Date();
			O2oEaLoanDataEnity eaLoanDataEnity = new O2oEaLoanDataEnity();
			eaLoanDataEnity.setPayId(o2oPayEntity.getId());
			eaLoanDataEnity.setBillCode(o2oPayEntity.getBillCode());
			eaLoanDataEnity.setBillCodeEa(o2oPayEntity.getLoanapplyBillcode());
			eaLoanDataEnity.setApplyAmount(o2oPayEntity.getLoanAmount());
			// 终端贷放款银行
			O2oZxEntity o2oZxEntity=new O2oZxEntity();
			if (loanUser!=null) {
				o2oZxEntity=o2oZxServiceImpl.getEntityById(loanUser.getZxNo());
			}
			eaLoanDataEnity.setLoanBank(o2oZxEntity.getZxBank());
			eaLoanDataEnity.setLoanAmount(loan.getEaMount());
			eaLoanDataEnity.setLoanerCard(loanUser.getDocumentNo());
			eaLoanDataEnity.setLoanerName(loanUser.getUserFullName());
			eaLoanDataEnity.setStatus("NEW");
			if (StatusContexts.PAY_TYPE_DF.equals(o2oPayEntity.getPayType()))
				eaLoanDataEnity.setPayTerm("0");
			else
				eaLoanDataEnity.setPayTerm(o2oPayEntity.getLoanTerm());
			// 终端贷的期数
			String loanTerm = bankCardService.getBankTerm(loan.getBillCode());
			int intloanTerm = 0;
			if(StringUtil.isNotBlank(loanTerm))
			{
				intloanTerm = Integer.parseInt(loanTerm);
			}
			eaLoanDataEnity.setLoanTerm(intloanTerm);
			eaLoanDataEnity.setIsDel("N");
			eaLoanDataEnity.setDataType("1");
			eaLoanDataEnity.setLoanDate(loan.getPaymentTime());
			eaLoanDataEnity.setOprateTime(date);
			eaLoanDataEnity.setUpdateTime(date);
			// 省区id \name
			String sql = "select oll.* from o2o_platform_regional oll where oll.platform_id=?";
			O2oPlatformRegional o2oPlatformRegional = o2oBrandDao.findEntity(sql, O2oPlatformRegional.class, loan.getLtd());
			eaLoanDataEnity.setProvince(o2oPlatformRegional.getProvinceCode());
			eaLoanDataEnity.setProvinceName(o2oPlatformRegional.getProvinceName());
			eaLoanDataEnity.setLtd(loan.getLtd());
			eaLoanDataEnity.setLtdCode(loan.getLtdCode());
			eaLoanDataEnity.setLtdName(loan.getLtdName());

			eaLoanDataEnity.setPayDate(o2oPayEntity.getPayDate());
			eaLoanDataEnity.setPayAmount(o2oPayEntity.getPayAmount());
			eaLoanDataEnity.setPayType(o2oPayEntity.getPayType());
			if (StatusContexts.PAY_TYPE_DF.equals(o2oPayEntity.getPayType()))
				eaLoanDataEnity.setLoanType(o2oPayEntity.getLoanType());
			else
				eaLoanDataEnity.setLoanType(loanapplyEntity.getLoanType());
			log.info("付款数据：{}", eaLoanDataEnity);
			int i = wfStatusDao.insert(eaLoanDataEnity);
			log.info("插入不良贷款数据是否成功(大于1成功，小于1失败):{}", i);
			// 插入还款记录表
			// O2oBadRecordEntity badRecordEntity = new O2oBadRecordEntity();
			// badRecordEntity.setBillCode(o2oPayEntity.getLoanapplyBillcode());
			// badRecordEntity.setLoanapplyNo(o2oPayEntity.getLoanapplyid());
			// badRecordEntity.setFlowStatus(StatusContexts.O2O_NEW);
			// badRecordEntity.setNewTime(new Date());
			// badRecordEntity.setNowArrears(o2oPayEntity.getPayAmount());
			// badRecordEntity.setNowShouldCapital(o2oPayEntity.getPayAmount());
			// badRecordEntity.setIsDelete(StatusContexts.O2O_NO);
			// int j = wfStatusDao.insert(badRecordEntity);
			// log.info("插入不良贷款还款记录数据是否成功(大于1成功，小于1失败):{}", j);
			// 修改付费流程状态
			o2oPayServiceImpl.updateEntityById(o2oPayEntity);
			// 代偿结束更新主表状态为DC，代偿
			log.info("loanapplyEntity:{}", loanapplyEntity.toString());
			loanapplyEntity.setEndDate(date);
			o2oLoanapplyService.updateEntityById(loanapplyEntity);
			log.info("付款流程结束，付款类型为：{}，是否为直贷:{}", o2oPayEntity.getPayType(), StatusContexts.PAY_TYPE_ZD.equals(o2oPayEntity.getPayType()));
			if (!o2oPayEntity.getBillCode().contains("O2O")) {
				return new ModelResult<>("workflow.notify.insert.error", "付费流程通知失败");
			}
			// 发送邮件
			log.info("放款银行为：{}，付款类型为:{}", loan.getBankLoanName(), o2oPayEntity.getPayType());
			// 符合国安村镇银行和垫付的发送邮件
			if (o2oPayEntity.getPayType().equals("DF")) {

				log.info("已经进入发邮件流程");
				List<String> roleCodelist = new ArrayList<String>();
				roleCodelist.add("1007");// 信贷经理
				// if
				// (!StatusContexts.O2O_LTD_CODE_S01163.equals(loan.getBuybackCode()))
				// {
				if (StatusContexts.OPERATION_MODEL_PTDB.equals(loan.getOperationModel())) {
					roleCodelist.add("1006");// 平台总经理
				}
				if ("GACZ".equals(loanapplyEntity.getBankLoanName())) {
					roleCodelist.add("1008");// 省区风控经理
					roleCodelist.add("O2O-SHJRZJ");// 省区金融总监
				}
				//
				ModelResult<List<User>> userListModel = sysPermissionService.getUserWithUnitNoAndRoleCode(loan.getLtd(), roleCodelist);
				String sentToEmailUrl = "";
				if (userListModel.isSuccess()) {
					for (User user : userListModel.getModel()) {
						sentToEmailUrl = sentToEmailUrl + user.getEmail() + ",";
					}
				}
				if (StringUtils.isNotBlank(sentToEmailUrl)) {
					sentToEmailUrl = sentToEmailUrl.substring(0, sentToEmailUrl.length() - 1);
					// 邮件发送需要的参数类
					MailNotifyRequest mailNotifyRequest = new MailNotifyRequest();
					mailNotifyRequest.setSystemCode("业务系统");
					mailNotifyRequest.setMailSendType(MailSendType.INSTANT);
					mailNotifyRequest.setBizCode("DF_" + o2oPayEntity.getBillCode());
					mailNotifyRequest.setRequestId(UuidUtil.generateShortUuid());
					mailNotifyRequest.setTitle("客户代偿信息通知");
					mailNotifyRequest.setRecipientTo(sentToEmailUrl);
					mailNotifyRequest.setRequestDateTime(new Date());
					// 生成邮件内容
					DFEmailContentVO contentVo = new DFEmailContentVO();
					String bankName = o2oPubDdItemService.findPubdditemNameByCode("BANKTYPEO2O", loan.getBankLoanName());
					contentVo.setTitle("客户代偿信息通知");
					contentVo.setBillCode(o2oPayEntity.getBillCode());
					contentVo.setDcTime(o2oPayEntity.getPayDate());
					contentVo.setDcAmount(o2oPayEntity.getPayAmount());
					contentVo.setLtdName(loan.getLtdName());
					contentVo.setLoanerName(loanUser.getUserFullName());
					contentVo.setRefundTime(loan.getPaymentTime());
					contentVo.setRefundAmount(o2oPayEntity.getLoanAmount());
					contentVo.setRefundBank(bankName);
					String content = convertEmailContent(contentVo);
					if (StringUtils.isNotBlank(content)) {
						mailNotifyRequest.setContent(content);
						mailNotifier.notify(mailNotifyRequest);
						log.info("referCode:[{}],sentToEmailUrl,开始发送邮件入库成功", o2oPayEntity.getBillCode(), sentToEmailUrl);
					} else {
						log.info("referCode:[{}],sentToEmailUrl:[{}],toList:[{}],生成邮件内容为空", o2oPayEntity.getBillCode(), sentToEmailUrl);
					}
				}

			}

		} else if (notifyParam.getProcessStatus() == ProcessTaskMain.PROECESS_STATUS_TURNED_DOWN) {
			log.info("付款驳回：{}", notifyParam.getReferId());
			O2oPayEntity o2oPayEntity = new O2oPayEntity();
			o2oPayEntity = o2oPayServiceImpl.findById(notifyParam.getReferId());
			log.info("付款查询：{}", o2oPayEntity);
			o2oPayEntity.setBillStatus(StatusContexts.WFTYPE_STATUS_NEW);
			// 修改付费流程状态
			o2oPayServiceImpl.updateEntityById(o2oPayEntity);
		} else if (notifyParam.getProcessStatus().equals(ProcessTaskMain.PROECESS_STATUS_REJECT)) {
			log.info("付款否决：{}", notifyParam.getReferId());
			O2oPayEntity o2oPayEntity = new O2oPayEntity();
			o2oPayEntity = o2oPayServiceImpl.findById(notifyParam.getReferId());
			log.info("付款查询：{}", o2oPayEntity);
			o2oPayEntity.setBillStatus(StatusContexts.WFTYPE_STATUS_NEW);
			// 修改付费流程状态
			o2oPayServiceImpl.updateEntityById(o2oPayEntity);
		}
		return new ModelResult<Boolean>().withModel(Boolean.TRUE);
	}

	/**
	 * @Description:
	 * 				<p>
	 *               代还款流程
	 *               </p>
	 * @author CXW
	 * @date 2017年5月19日 上午9:37:31
	 * @version V1.0
	 */

	public ModelResult<Boolean> generation(WFNotifyParam notifyParam, O2oLoanapplyEntity loanapplyEntity) {
		if (notifyParam.getProcessStatus() == ProcessTaskMain.PROECESS_STATUS_PASS) {
			O2oGenerationEntity generationEntity = generationService.getById(notifyParam.getReferId());
			log.info("代还款流程通过通知查询：{}", generationEntity.toString());
			generationEntity.setFlowEndTime(new Date());
			generationEntity.setFlowStatus(StatusContexts.WFTYPE_STATUS_CLO);
			int i = generationService.update(generationEntity);
			log.info("代还款流程通过通知更新更新是否成功，1为成功：{}", i);
			log.info("代还款流程通过通知更新后：{}", generationEntity.toString());
		} else if (notifyParam.getProcessStatus() == ProcessTaskMain.PROECESS_STATUS_TURNED_DOWN) {
			O2oGenerationEntity generationEntity = generationService.getById(notifyParam.getReferId());
			log.info("代还款流程驳回通知查询：{}", generationEntity.toString());
			generationEntity.setFlowStatus(StatusContexts.WFTYPE_STATUS_NEW);
			int i = generationService.update(generationEntity);
			log.info("代还款流程驳回通知更新更新是否成功，1为成功：{}", i);
			log.info("代还款流程驳回通知更新后：{}", generationEntity.toString());
		} else if (notifyParam.getProcessStatus().equals(ProcessTaskMain.PROECESS_STATUS_REJECT)) {
			O2oGenerationEntity generationEntity = generationService.getById(notifyParam.getReferId());
			log.info("代还款流程否决通知查询：{}", generationEntity.toString());
			generationEntity.setFlowStatus(StatusContexts.WFTYPE_STATUS_NEW);
			generationEntity.setIsDellete(StatusContexts.O2O_YES);
			int i = generationService.update(generationEntity);
			log.info("代还款流程否决通知更新更新是否成功，1为成功：{}", i);
			log.info("代还款流程否决通知更新后：{}", generationEntity.toString());
		}
		return new ModelResult<Boolean>().withModel(Boolean.TRUE);
	}

	/**
	 * @Description:
	 * 				<p>
	 *               需求申请
	 *               </p>
	 * @author THQ
	 * @date 2016年12月14日 下午2:47:43
	 * @version V1.0
	 */
	public ModelResult<Boolean> financeDemand(WFNotifyParam notifyParam) {
		try {
			MainApply mainApply = ticketMainApplyService.findMainApplyById(notifyParam.getReferId());
			// 0同意，1否决，2处理中
			if (notifyParam.getProcessStatus() == ProcessTaskMain.PROECESS_STATUS_PASS) {// 处理完成
				// 修改状态为CLO 增加结束时间
				mainApply.setBillStatus(StatusContexts.WFTYPE_STATUS_CLO);
				Date nowDate = new Date();
				mainApply.setEndDate(nowDate);
				mainApply.setUpdateDate(nowDate);
				mainApply.setUpdator(notifyParam.getAppliedbyName());
				mainApply.setUpdatorId(notifyParam.getAppliedby());
				log.info("ReferId:[{}],需求申请流程结束成功", notifyParam.getReferId());
			} else if (notifyParam.getProcessStatus() == ProcessTaskMain.PROECESS_STATUS_TURNED_DOWN) {// 驳回
				// 驳回 修改 当前流程类型的 状态为BH
				// 修改状态为BH
				mainApply.setBillStatus(StatusContexts.WFTYPE_STATUS_BH);
				Date nowDate = new Date();
				mainApply.setUpdateDate(nowDate);
				mainApply.setUpdator(notifyParam.getAppliedbyName());
				mainApply.setUpdatorId(notifyParam.getAppliedby());
				log.info("ReferId:[{}],需求申请驳回成功", notifyParam.getReferId());
			}
			log.info("ReferId:[{}],插入请求的日志信息表开始", notifyParam.getReferId());
			int effectRows1 = ticketMainApplyService.updateMainApplyByEntity(mainApply);
			if (effectRows1 == 1) {
				log.info("ReferId:[{}],修改主表状态成功", notifyParam.getReferId());
			} else {
				log.info("ReferId:[{}],修改主表状态失败", notifyParam.getReferId());
			}
			log.info("ReferId:[{}],需求申请回调结束", notifyParam.getReferId());
			return new ModelResult<Boolean>().withModel(Boolean.TRUE);
		} catch (Exception e) {
			log.info("需求申请：ReferId[{}],ProcessType[{}]", notifyParam.getReferId(), notifyParam.getProcessType());
			return new ModelResult<>("workflow.notify.insert.error", "流程通知插入失败");
		}
	}

	@Value("${o2o.admin.mq.host}")
	String host;

	@Value("${o2o.admin.mq.username}")
	String username;

	@Value("${o2o.admin.mq.password}")
	String password;

	/**
	 * @Description:
	 * 				<p>
	 *               回款流程
	 *               </p>
	 * @author CXW
	 * @date 2016年12月23日 下午4:45:33
	 * @version V1.0
	 */
	public ModelResult<Boolean> badLoanBack(WFNotifyParam notifyParam) {
		// 回款流程通过
		if (notifyParam.getProcessStatus() == ProcessTaskMain.PROECESS_STATUS_PASS) {
			log.info("ReferId:[{}],回款流程结束成功", notifyParam.getReferId());
			Date date = new Date();
			O2oBadRecordEntity entity = service.getByBadRecordID(notifyParam.getReferId());
			O2oEaLoanDataEnity o2oEaLoanDataEnity = service.findById(entity.getLoanDataId());
			entity.setFlowEndTime(date);
			entity.setFlowStatus(StatusContexts.O2O_BANK_CLO);
			// 计算本次应还总额，减去本次已还总额，等于本次回款后当前欠款余额
			BigDecimal nowArrears = calculationNowArrears(entity, o2oEaLoanDataEnity);
			log.info("当前欠款余额，{}", nowArrears);
			entity.setNowArrears(nowArrears);
			log.info("更新回款记录，{}", entity);
			int i = service.updateByBadRecordID(entity);
			log.info("更新回款记录成功或失败：【{}】", i);
			if (i > 0) {
				O2oEaLoanDataEnity dataEnity = service.findByLoanDataId(entity.getLoanDataId());
				BigDecimal thisPayment = new BigDecimal(0);
				if (dataEnity.getPaymentAmount() != null) {
					thisPayment = dataEnity.getPaymentAmount().add(entity.getThisPaymentPrincipal());
				} else {
					thisPayment = entity.getThisPaymentPrincipal();
				}
				dataEnity.setPayAreas(nowArrears);
				dataEnity.setPaymentAmount(thisPayment);
				dataEnity.setUpdateTime(date);
				int j = wfStatusDao.updateById(dataEnity);
				if (j > 0) {
					log.info("更新O2oEaLoanDataEnity成功:[{}]", dataEnity.getBillCode());
					return new ModelResult<Boolean>().withModel(Boolean.TRUE);
				} else {
					log.info("更新O2oEaLoanDataEnity失败:[{}]", dataEnity.getBillCode());
					return new ModelResult<>("workflow.notify.insert.error", "回款流程通过通知失败");
				}
			} else {
				return new ModelResult<>("workflow.notify.insert.error", "回款流程通过通知失败");
			}
		} else if (notifyParam.getProcessStatus() == ProcessTaskMain.PROECESS_STATUS_TURNED_DOWN) {
			log.info("ReferId:[{}],回款流程结束驳回", notifyParam.getReferId());
			// 回款流程驳回
			O2oBadRecordEntity entity = service.getByBadRecordID(notifyParam.getReferId());
			entity.setFlowStatus(StatusContexts.O2O_BANK_NEW);
			log.info("更新回款记录，{}", entity);
			int i = service.updateByBadRecordID(entity);
			log.info("更新回款记录成功或失败：【{}】", i);
			if (i > 0) {
				return new ModelResult<Boolean>().withModel(Boolean.TRUE);
			} else {
				return new ModelResult<>("workflow.notify.insert.error", "回款流程驳回通知失败");
			}
		} else if (notifyParam.getProcessStatus().equals(ProcessTaskMain.PROECESS_STATUS_REJECT)) {
			log.info("ReferId:[{}],回款流程作废", notifyParam.getReferId());
		}
		return new ModelResult<Boolean>().withModel(Boolean.TRUE);
	}

	/**
	 * @Description:
	 * 				<p>
	 *               计算余额
	 *               </p>
	 * @author CXW
	 * @date 2017年2月22日 下午3:01:56
	 * @version V1.0
	 */
	public BigDecimal calculationNowArrears(O2oBadRecordEntity entity, O2oEaLoanDataEnity dataEnity) {
		int number = service.findCountByBillCode(entity.getBillCode());
		BigDecimal interest = new BigDecimal(0);
		BigDecimal thisNowArrear = new BigDecimal(0);
		Calendar nowDate = Calendar.getInstance(), oldDate = Calendar.getInstance();
		nowDate.setTime(entity.getThisPaymentDate());
		if (number < 1) {// 第一笔代偿利息起始计算日以代偿流程中的付款时间为准
			oldDate.setTime(dataEnity.getPayDate());// 设置为1990年（6）月29日
		} else {// 非第一笔代偿利息以上一次流程中总部财务复核的“收款时间”开始计算
			String dateStr = service.findPayDateByBillCode(entity.getBillCode());// 查询“收款时间”
			Date date = DateUtils.formateStandDate(dateStr);
			oldDate.setTime(date);
		}
		long timeNow = nowDate.getTimeInMillis();
		long timeOld = oldDate.getTimeInMillis();
		long nowTime = (timeNow - timeOld) / (1000 * 60 * 60 * 24);// 化为天
		nowTime = nowTime < 0 ? 0 : nowTime;// 如果天数小于0，值为零
		if (number < 1) {
			interest = dataEnity.getPayAmount().multiply(new BigDecimal(nowTime)).multiply(new BigDecimal(0.15 / 360));
			thisNowArrear = dataEnity.getPayAmount().add(interest).subtract(entity.getThisPaymentPrincipal());
		} else {
			interest = entity.getNowArrears().multiply(new BigDecimal(nowTime)).multiply(new BigDecimal(0.15 / 360));
			thisNowArrear = entity.getNowArrears().add(interest).subtract(entity.getThisPaymentPrincipal());
		}
		thisNowArrear = thisNowArrear.setScale(2, RoundingMode.HALF_UP);
		if (thisNowArrear.compareTo(new BigDecimal(0)) == -1) {
			thisNowArrear = new BigDecimal(0);
		}
		return thisNowArrear;
	}

	/**
	 * 各个节点通过的处理
	 * 
	 * @param notifyParam
	 * @param loanapplyEntity
	 * @return
	 */
	private ModelResult<Boolean> dealNodecode(WFNotifyParam notifyParam, O2oLoanapplyEntity loanapplyEntity) {
		if (notifyParam.getProcessType().equals(ProcessTemplate.PROECESS_TYPE_BANK_REPORT) || notifyParam.getProcessType().equals(ProcessTemplate.PROECESS_TYPE_BANK_REPORT_FQ)) // 面签申报
		{
			log.info("billCode:[{}],进入面签申报流程中：", loanapplyEntity.getBillCode());
			// 判断节点codeR
			if (StatusContexts.O2O_WF_CODE_MQ_MQ003.equals(notifyParam.getTaskNode().getNodeCode())) { // 面签申报
				// 银行申报审查节点
				// loan-12698 新增批量确认放款数据功能 过了面签申报银行审查申报节点的贷款单（做标记）
				loanapplyEntity.setDeclareSign("Y");									
				loanapplyEntity.setEndDate(new Date());
				o2oLoanapplyService.updateEntityById(loanapplyEntity);
				// loan-12698 新增批量确认放款数据功能 过了面签申报银行审查申报节点的贷款单（做标记）
				
				String bank_type = loanapplyEntity.getBankLoanName(); // 放款银行
				if (StatusContexts.O2O_BANKTYPE_BC.equals(bank_type) || StatusContexts.O2O_BANKTYPE_CCBHN.equals(bank_type) || StatusContexts.O2O_BANKTYPE_CBC.equals(bank_type) || StatusContexts.O2O_BANKTYPE_GACZ.equals(bank_type)) {
					try {// 面签申报完成之后发送短信
						ModelResult<Boolean> messageResult = o2oMessageServiceImpl.mqsbMessage(loanapplyEntity.getBillCode());
						if (messageResult.getModel()) { // 如果是返回的是true，说明是成功的
							log.info("billCode:[{}],面签申报 银行申报审查节点通过后给客户 发送通知短信成功", loanapplyEntity.getBillCode());
						} else {
							log.error("billCode:[{}],面签申报 银行申报审查节点通过后给客户 发送通知短信失败", loanapplyEntity.getBillCode());
						}
					} catch (Exception e) {
						log.error("billCode:[{}],面签申报 银行申报审查节点通过后给客户 发送通知短信失败：", loanapplyEntity.getBillCode());
					}
				}
			}

		}
		if (notifyParam.getProcessType().equals("CREDIT_INQUIRY")) {
			log.info("进入流程处理中--新征信notifyParam.getReferId()={}",notifyParam.getReferId());
			String referId =notifyParam.getReferId();
			O2oZxEntity o2oZxEntity =o2oZxServiceImpl.getEntityById(referId);
			if (o2oZxEntity!=null) {
				o2oZxEntity.setBcisagree("Y");
				o2oZxServiceImpl.update(o2oZxEntity);
			}
		}
		return new ModelResult<Boolean>().withModel(Boolean.TRUE);
	}

	/**
	 * @Title: convertEmailContent
	 * @Description:封装发送邮件模板
	 * @author 张庆奇
	 * @param vo
	 * @return
	 * @return String
	 * @throws @date
	 *             2017年3月9日 下午2:07:49
	 */
	private String convertEmailContent(DFEmailContentVO vo) {
		// 通过指定模板名获取FreeMarker模板实例
		try {
			Configuration configuration = new Configuration(Configuration.VERSION_2_3_24);
			configuration.setTemplateLoader(new ClassTemplateLoader(this.getClass(), "/email/"));
			Template template = configuration.getTemplate("dcEmailTemplate.ftl");
			StringWriter stringWriter = new StringWriter();
			// FreeMarker通过Map传递动态数据
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("email", vo);
			template.process(map, stringWriter);
			String htmlText = stringWriter.toString();
			return htmlText;
		} catch (Exception e) {
			log.error("生成邮件模板失败", e);
		}
		return null;
	}

	/**
	 * @Description:
	 * 				<p>
	 *               特殊面签申报通知处理
	 *               </p>
	 * @author yy
	 * @date 2017年3月09日 上午10:01:56
	 * @version V1.0
	 */
	public ModelResult<Boolean> updateSpecialInterview(WFNotifyParam notifyParam) {
		O2OSpecialInterview o2OSpecialInterview = o2OSpecialInterviewService.queryEntity(notifyParam.getReferId());
		// 特殊面签申报通过
		if (notifyParam.getProcessStatus() == ProcessTaskMain.PROECESS_STATUS_PASS) {
			log.info("ReferId:[{}],特殊面签申报结束成功", notifyParam.getReferId());
			o2OSpecialInterview.setBillStatus(StatusContexts.O2O_BANK_CLO); // 结束
			int i = o2OSpecialInterviewService.update(o2OSpecialInterview);
			if (i > 0) {
				return new ModelResult<Boolean>().withModel(Boolean.TRUE);
			} else {
				return new ModelResult<>("workflow.notify.insert.error", "特殊面签申报通过通知失败");
			}
		} else if (notifyParam.getProcessStatus() == ProcessTaskMain.PROECESS_STATUS_TURNED_DOWN) {
			log.info("ReferId:[{}],特殊面签申报结束驳回", notifyParam.getReferId());
			// 特殊面签申报驳回
			o2OSpecialInterview.setBillStatus(StatusContexts.O2O_BANK_NEW);
			int i = o2OSpecialInterviewService.update(o2OSpecialInterview);
			log.info("更新特殊面签申报记录成功或失败：【{}】", i);
			if (i > 0) {
				return new ModelResult<Boolean>().withModel(Boolean.TRUE);
			} else {
				return new ModelResult<>("workflow.notify.insert.error", "回款流程驳回通知失败");
			}
		} else if (notifyParam.getProcessStatus().equals(ProcessTaskMain.PROECESS_STATUS_REJECT)) {
			log.info("ReferId:[{}],回款流程作废", notifyParam.getReferId());
		}
		return new ModelResult<Boolean>().withModel(Boolean.TRUE);
	}

	@Autowired
	private O2oBackService o2oBackService;

	/**
	 * @Description:
	 * 				<p>
	 *               代偿分期流程
	 *               </p>
	 * @author CXW
	 * @date 2017年3月10日 下午1:53:33
	 * @version V1.0
	 */
	public ModelResult<Boolean> backFlow(WFNotifyParam notifyParam) {
		// 代偿分期流程通过
		if (notifyParam.getProcessStatus() == ProcessTaskMain.PROECESS_STATUS_PASS) {
			log.info("ReferId:[{}],代偿分期流程束成功", notifyParam.getReferId());
			Date date = new Date();
			O2oBackEntity backEntity = o2oBackService.getEntityById(notifyParam.getReferId());
			backEntity.setFlowEndtime(date);
			backEntity.setEndUpdateTime(date);
			backEntity.setFlowStatus(StatusContexts.O2O_BANK_CLO);
			int i = o2oBackService.update(backEntity);
			if (i > 0) {
				log.info("ReferId:[{}],代偿分期流程束更新成功", notifyParam.getReferId());
			}
		} else if (notifyParam.getProcessStatus() == ProcessTaskMain.PROECESS_STATUS_TURNED_DOWN) {
			log.info("ReferId:[{}],代偿分期流程驳回", notifyParam.getReferId());
			Date date = new Date();
			O2oBackEntity backEntity = o2oBackService.getEntityById(notifyParam.getReferId());
			backEntity.setEndUpdateTime(date);
			backEntity.setFlowStatus(StatusContexts.O2O_BANK_NEW);
			int i = o2oBackService.update(backEntity);
			if (i > 0) {
				log.info("ReferId:[{}],代偿分期流程驳回更新成功", notifyParam.getReferId());
			}
		} else if (notifyParam.getProcessStatus().equals(ProcessTaskMain.PROECESS_STATUS_REJECT)) {
			log.info("ReferId:[{}],代偿分期流程作废", notifyParam.getReferId());
			Date date = new Date();
			O2oBackEntity backEntity = o2oBackService.getEntityById(notifyParam.getReferId());
			backEntity.setEndUpdateTime(date);
			backEntity.setIsDelete(StatusContexts.O2O_YES);
			int i = o2oBackService.update(backEntity);
			if (i > 0) {
				log.info("ReferId:[{}],代偿分期流程作废更新成功", notifyParam.getReferId());
			}
		}
		return new ModelResult<Boolean>().withModel(Boolean.TRUE);
	}

	/**
	 * 归档借阅流程
	 * 
	 * @param notifyParam
	 * @return
	 */
	private ModelResult<Boolean> notifyGDBorrow(WFNotifyParam notifyParam) {
		String state = null;
		log.info("归档借阅消息通知:[{}]", notifyParam.getProcessType());
		if (notifyParam.getProcessStatus() == ProcessTaskMain.PROECESS_STATUS_PASS) {
			log.info("归档借阅流程通过记录通知：{}", notifyParam.getReferId());
			state = ArchiveBorrowEntity.wf_state_pass;
		} else if (notifyParam.getProcessStatus() == ProcessTaskMain.PROECESS_STATUS_TURNED_DOWN) {
			log.info("归档借阅流程驳回记录通知：{}", notifyParam.getReferId());
			state = ArchiveBorrowEntity.wf_state_new;
		} else if (notifyParam.getProcessStatus().equals(ProcessTaskMain.PROECESS_STATUS_REJECT)) {
			log.info("归档借阅流程作废记录通知：{}", notifyParam.getReferId());
			state = ArchiveBorrowEntity.wf_state_reject;
		}
		if (StringUtils.isNotBlank(state))
			archiveBorrowService.updateBorrowState(notifyParam.getReferId(), state);

		return new ModelResult<Boolean>().withModel(Boolean.TRUE);
	}

	/**
	 * 补充归档流程
	 * 
	 * @param notifyParam
	 * @return
	 */
	private ModelResult<Boolean> notifyGDBC(WFNotifyParam notifyParam) {
		archiveRecordDao.updateArchiveRepeatState(notifyParam.getReferId(), notifyParam.getProcessStatus());
		// 审核通过--同步新增数据到归档详情
		if (notifyParam.getProcessStatus() == ProcessTaskMain.PROECESS_STATUS_PASS) {
			ArchiveRecordRepeatEntity varRecord = archiveRecordDao.queryArchiveRepeatRecordById(notifyParam.getReferId());
			//存柜资料
			calcBcGd(varRecord,ArchiveConstants.FORMTYPE_ARCHIVE_INFO);
			//财务存柜资料
			calcBcGd(varRecord,ArchiveConstants.FORMTYPE_FINANCE);
		}
		return new ModelResult<Boolean>().withModel(Boolean.TRUE);
	}
	
	private void calcBcGd(ArchiveRecordRepeatEntity varRecord,String formTypeId){
		List<FieldEntity> fields = archiveService.getFieldListAll();
		String loanapplyNo = varRecord.getLoanapplyNo();
		String bankTypeId = varRecord.getBankTypeId();
		String varJson = null;// 增量数据
		if(StringUtils.equals(formTypeId, ArchiveConstants.FORMTYPE_ARCHIVE_INFO))
			varJson = varRecord.getContentJson();
		else if(StringUtils.equals(formTypeId, ArchiveConstants.FORMTYPE_FINANCE))
			varJson = varRecord.getCwContentJson(); 
		
		if(StringUtils.isNotBlank(varJson) && !StringUtils.equals(varJson.trim(), "{}")){
			JSONObject obj = JSONObject.parseObject(varJson);
			Iterator<FieldEntity> iterator = fields.iterator();
			while (iterator.hasNext()) {
				FieldEntity f = iterator.next();
				String fieldValue = obj.getString(f.getFieldName());
				if (StringUtils.isBlank(fieldValue))
					iterator.remove();
				else
					f.setFieldValue(fieldValue);
			}
			ArchiveRecordEntity initRecord = archiveRecordDao.queryArchiveRecord(loanapplyNo, bankTypeId, formTypeId);
			String initJson = initRecord.getContentJson();// 原始数据
			JSONObject obj2 = JSONObject.parseObject(initJson);
			for (FieldEntity f : fields) {
				String fieldValue = obj2.getString(f.getFieldName());
				if (fieldValue != null) {
					int val = Integer.parseInt(fieldValue) + Integer.parseInt(f.getFieldValue());
					obj2.put(f.getFieldName(), val + "");
				} else {
					obj2.put(f.getFieldName(), f.getFieldValue());
					O2oDeployFileLink link = new O2oDeployFileLink();
					link.setBankTypeId(bankTypeId);
					link.setFormTypeId(formTypeId);
					link.setFiledId(f.getFieldId());
					link.setFieldMin(0);
					link.setFiledMax(10);
					link.setFieldRequired(0);
					link.setCreator("Admintisor");
					link.setCreate_time(new Date());
					deployFileDao.insert(link);
				}
			}
			archiveRecordDao.updateArchiveRecordContentJson(initRecord.getId(), obj2.toJSONString());
		}
	}

	/**
	 * 征信归档
	 * 
	 * @param notifyParam
	 */
	private CreditArchiveRecordEntity zxgdFlow(WFNotifyParam notifyParam) {
		CreditArchiveRecordEntity creditArchiveRecordEntity = creditArchiveService.getCreditArchiveRecordById(notifyParam.getReferId());
		if (notifyParam.getProcessStatus() == ProcessTaskMain.PROECESS_STATUS_PASS) {// 流程通过
			creditArchiveRecordEntity.setStatus(StatusContexts.ZXGD_CLO);
			creditArchiveRecordEntity.setWfStatus(StatusContexts.ZXGD_CLO);
			boolean flag = creditArchiveService.updateCreditArchiveRecordEntity(creditArchiveRecordEntity);
			if (!flag) {
				log.info("征信归档编号:[{}],货款单号：[{}],征信归档完成,修改失败", creditArchiveRecordEntity.getId(), creditArchiveRecordEntity.getBillCode());
				throw new RuntimeException();
			}
			log.info("征信归档编号:[{}],货款单号：[{}],征信归档流程完成,修改状态为：[{}]", creditArchiveRecordEntity.getId(), creditArchiveRecordEntity.getBillCode(), StatusContexts.ZXGD_CLO);
		} else if (notifyParam.getProcessStatus() == ProcessTaskMain.PROECESS_STATUS_TURNED_DOWN) {// 流程驳回
			creditArchiveRecordEntity.setStatus("NEW");
			creditArchiveRecordEntity.setWfStatus("NEW");
			boolean flag = creditArchiveService.updateCreditArchiveRecordEntity(creditArchiveRecordEntity);
			if (!flag) {
				log.info("征信归档编号:[{}],货款单号：[{}],征信归档驳回,修改失败", creditArchiveRecordEntity.getId(), creditArchiveRecordEntity.getBillCode());
				throw new RuntimeException();
			}
			log.info("征信归档编号:[{}],货款单号：[{}],征信归档流程驳回", creditArchiveRecordEntity.getId(), creditArchiveRecordEntity.getBillCode(), "NEW");
		} else if (notifyParam.getProcessStatus().equals(ProcessTaskMain.PROECESS_STATUS_REJECT)) {// 作废
			creditArchiveRecordEntity.setStatus(StatusContexts.ZXGD_ZF);
			boolean flag = creditArchiveService.updateCreditArchiveRecordEntity(creditArchiveRecordEntity);
			if (!flag) {
				log.info("征信归档编号:[{}],货款单号：[{}],征信归档作废,修改失败", creditArchiveRecordEntity.getId(), creditArchiveRecordEntity.getBillCode());
				throw new RuntimeException();
			}
			log.info("征信归档编号:[{}],货款单号：[{}],征信归档流程作废", creditArchiveRecordEntity.getId(), creditArchiveRecordEntity.getBillCode(), StatusContexts.ZXGD_ZF);
		}
		return creditArchiveRecordEntity;
	}

	@Autowired
	O2oSettleService o2oSettleService;

	/**
	 * @Description:
	 * 				<p>
	 *               代偿结清流程
	 *               </p>
	 * @author CXW
	 * @date 2017年4月20日 下午3:15:54
	 * @version V1.0
	 */
	private ModelResult<Boolean> settleFlow(WFNotifyParam notifyParam) {
		// 代偿结清流程通过
		if (notifyParam.getProcessStatus() == ProcessTaskMain.PROECESS_STATUS_PASS) {
			log.info("ReferId:[{}],代偿结清流程结束成功", notifyParam.getReferId());
			O2oSettleVo vo = new O2oSettleVo();
			vo.setEaLoadId(notifyParam.getReferId());
			O2oSettleEntity o2oSettleEntity = o2oSettleService.findEntity(vo);
			o2oSettleEntity.setFlowEndTime(new Date());
			o2oSettleEntity.setFlowStatus(StatusContexts.O2O_BANK_CLO);
			int i = o2oSettleService.updateById(o2oSettleEntity);
			if (i > 0) {
				log.info("代偿结清流程结束更新成功");
				O2oEaLoanDataEnity o2oEaLoanDataEnity = service.findById(notifyParam.getReferId());
				O2oLoanapplyEntity o2oLoanapplyEntity = o2oLoanapplyService.findBillCode1(o2oEaLoanDataEnity.getBillCodeEa());
				if (!StringUtils.isEmpty(o2oEaLoanDataEnity.getLoanType()) && o2oEaLoanDataEnity.getLoanType().equals("LXDC")) {// 为利息代偿
					if (!StringUtils.isEmpty(o2oLoanapplyEntity.getWfType()) && o2oLoanapplyEntity.getWfType().equals("YQ")) {// 主单状态为逾期
						o2oLoanapplyEntity.setWfType(StatusContexts.O2O_FK_END);// 修改为还款中
						o2oLoanapplyService.updateEntityById(o2oLoanapplyEntity);
					}
				}
			} else {
				log.info("代偿结清流程结束更新失败");
				throw new RuntimeException();
			}
		} else if (notifyParam.getProcessStatus() == ProcessTaskMain.PROECESS_STATUS_TURNED_DOWN) {
			log.info("ReferId:[{}],代偿结清流程结束驳回", notifyParam.getReferId());
			O2oSettleVo vo = new O2oSettleVo();
			vo.setEaLoadId(notifyParam.getReferId());
			O2oSettleEntity o2oSettleEntity = o2oSettleService.findEntity(vo);
			o2oSettleEntity.setFlowStatus(StatusContexts.O2O_BANK_NEW);
			int i = o2oSettleService.updateById(o2oSettleEntity);
			if (i > 0) {
				log.info("代偿结清流程结束驳回更新成功");
			} else {
				log.info("代偿结清流程结束驳回更新失败");
				throw new RuntimeException();
			}
		} else if (notifyParam.getProcessStatus().equals(ProcessTaskMain.PROECESS_STATUS_REJECT)) {
			log.info("ReferId:[{}],代偿结清流程作废", notifyParam.getReferId());
			O2oSettleVo vo = new O2oSettleVo();
			vo.setEaLoadId(notifyParam.getReferId());
			O2oSettleEntity o2oSettleEntity = o2oSettleService.findEntity(vo);
			o2oSettleEntity.setFlowEndTime(new Date());
			o2oSettleEntity.setFlowStatus(StatusContexts.O2O_FK_OVER);
			int i = o2oSettleService.updateById(o2oSettleEntity);
			if (i > 0) {
				log.info("代偿结清流程作废更新成功");
			} else {
				log.info("代偿结清流程作废更新失败");
				throw new RuntimeException();
			}
		}
		return new ModelResult<Boolean>().withModel(Boolean.TRUE);
	}
	
	
	@Autowired
	private O2oLoanSubmittedServiceImple o2oLoanSubmittedServiceImple;
	/**
	 * @Description:
	 *               <p>
	 *               案件报送通知
	 *               </p>
	 * @author CXW
	 * @date 2017年9月1日 上午10:39:19
	 * @version V1.0
	 */
	private ModelResult<Boolean> submitted(WFNotifyParam notifyParam) {
		O2oLoanSubmittedEntity o2oLoanSubmittedEntity = o2oLoanSubmittedServiceImple.getEntityById(notifyParam.getReferId());
		// 代偿结清流程通过
		if (notifyParam.getProcessStatus() == ProcessTaskMain.PROECESS_STATUS_PASS) {
			o2oLoanSubmittedEntity.setFlowEndTime(new Date());
			o2oLoanSubmittedEntity.setFlowStatus(StatusContexts.O2O_BANK_CLO);
			int i = o2oLoanSubmittedServiceImple.update(o2oLoanSubmittedEntity);
			if (i > 0) {
				log.info("案件报送流程通知 更新成功:[{}]", notifyParam.getReferId());
			} else {
				log.info("更新O2oLoanSubmittedEntity案件报送失败,流程id:[{}]", notifyParam.getReferId());
				return new ModelResult<>("workflow.notify.insert.error", "财务审核流程通过通知失败");
			}
		} else if (notifyParam.getProcessStatus() == ProcessTaskMain.PROECESS_STATUS_TURNED_DOWN) {
			o2oLoanSubmittedEntity.setFlowStatus(StatusContexts.O2O_NEW);
			int i = o2oLoanSubmittedServiceImple.update(o2oLoanSubmittedEntity);
			if (i > 0) {
				log.info("案件报送流程通知 更新成功:[{}]", notifyParam.getReferId());
			} else {
				log.info("更新O2oLoanSubmittedEntity案件报送失败,流程id:[{}]", notifyParam.getReferId());
				return new ModelResult<>("workflow.notify.insert.error", "财务审核流程通过通知失败");
			}
		}
		return new ModelResult<Boolean>().withModel(Boolean.TRUE);
	}
	
	
	/**
	 * @Description:
	 *               <p>
	 *               新征信通知
	 *               </p>
	 * @author yy
	 * @date 2017年9月8日 14:39:19
	 * @version V1.0
	 */
	private ModelResult<Boolean> noticeNZX(WFNotifyParam notifyParam) {
		
		O2oZxEntity o2oZxEntity  = o2oZxServiceImpl.getEntityById(notifyParam.getReferId());
		
		if (notifyParam.getProcessStatus() == ProcessTaskMain.PROECESS_STATUS_PASS) {
			o2oZxEntity.setZxStatus(StatusContexts.O2O_BANK_CLO);
			o2oZxEntity.setEndDate(new Date());
			int i = o2oZxServiceImpl.update(o2oZxEntity);
			if (i > 0) {
				log.info("新征信流程通知 更新成功:[{}]", notifyParam.getReferId());
				//更新关联的征信准入信息，如果征信准入信息为新建状态，并且启动该流程
				updateZxzrAndStart(notifyParam.getReferId());
			} else {
				log.info("更新o2oZxEntity新征信失败,流程id:[{}]", notifyParam.getReferId());
				return new ModelResult<>("workflow.notify.insert.error", "新征信流程通过通知失败");
			}
		} else if (notifyParam.getProcessStatus() == ProcessTaskMain.PROECESS_STATUS_TURNED_DOWN) { //驳回
			o2oZxEntity.setZxStatus(StatusContexts.O2O_NEW);
			int i = o2oZxServiceImpl.update(o2oZxEntity);
			if (i > 0) {
				log.info("新征信流程通知 更新成功:[{}]", notifyParam.getReferId());
			} else {
				log.info("更新o2oZxEntity新征信失败,流程id:[{}]", notifyParam.getReferId());
				return new ModelResult<>("workflow.notify.insert.error", "新征信流程通过通知失败");
			}
		}
		return new ModelResult<Boolean>().withModel(Boolean.TRUE);
	}
	
	
	/**
	 * @Description:
	 *               <p>
	 *               企业征信通知
	 *               </p>
	 * @author yy
	 * @date 2017年11月10日 14:39:19
	 * @version V1.0
	 */
	private ModelResult<Boolean> noticeQYZX(WFNotifyParam notifyParam) {
		
		O2oEnterpriseZxEntity o2oEnterpriseZxEntity  = o2oEnterpriseZxService.getEntityById(notifyParam.getReferId());
		if (notifyParam.getProcessStatus() == ProcessTaskMain.PROECESS_STATUS_PASS) {
			o2oEnterpriseZxEntity.setZxStatus(StatusContexts.O2O_BANK_CLO);
			o2oEnterpriseZxEntity.setEndDate(new Date());
			int i = o2oEnterpriseZxService.update(o2oEnterpriseZxEntity);
			if (i > 0) {
				log.info("企业征信流程通知 更新成功:[{}]", notifyParam.getReferId());
				//更新关联的征信准入信息，如果征信准入信息为新建状态，并且启动该流程
				updateZxzrAndStart(notifyParam.getReferId());
			} else {
				log.info("更新o2oEnterpriseZxEntity企业征信失败,流程id:[{}]", notifyParam.getReferId());
				return new ModelResult<>("workflow.notify.insert.error", "企业征信流程通过通知失败");
			}
		} else if (notifyParam.getProcessStatus() == ProcessTaskMain.PROECESS_STATUS_TURNED_DOWN) { //驳回
			o2oEnterpriseZxEntity.setZxStatus(StatusContexts.O2O_NEW);
			int i = o2oEnterpriseZxService.update(o2oEnterpriseZxEntity);
			if (i > 0) {
				log.info("企业征信流程通知 更新成功:[{}]", notifyParam.getReferId());
			} else {
				log.info("更新o2oEnterpriseZxEntity企业征信失败,流程id:[{}]", notifyParam.getReferId());
				return new ModelResult<>("workflow.notify.insert.error", "企业征信流程通过通知失败");
			}
		}
		return new ModelResult<Boolean>().withModel(Boolean.TRUE);
	}
	
	
	/**
	 * @Title: getWfType
	 * @Description: 根据模板类型返回流程类型
	 * @author 张庆奇
	 * @param notifyParam
	 * @return
	 * @return String
	 * @throws
	 * @date 2017年6月21日 下午5:43:38
	 */
	public String getWfType(WFNotifyParam notifyParam){
		String wfType="";
		if (notifyParam.getProcessType().equals(ProcessTemplate.PROECESS_TYPE_REQUIREMENT_APP) || notifyParam.getProcessType().equals(ProcessTemplate.PROECESS_TYPE_BUS_REQUIREMENT_APP) || notifyParam.getProcessType().equals(ProcessTemplate.PROECESS_TYPE_HQ_REQUIREMENT_APP) || notifyParam.getProcessType().equals(ProcessTemplate.PROECESS_TYPE_SYSTEM_DEV)) {
			wfType = StatusContexts.WFTYPE_REQUIREMENT_APP;
		} else if (notifyParam.getProcessType().equals(ProcessTemplate.PROECESS_TYPE_CREDIT) || notifyParam.getProcessType().equals(ProcessTemplate.PROECESS_TYPE_CREDI_FQ) || notifyParam.getProcessType().equals(ProcessTemplate.PROECESS_TYPE_CREDI_BP)) {
			// 征信流程
		
			wfType = StatusContexts.WFTYPE_ZX;
			
		} else if (notifyParam.getProcessType().equals(ProcessTemplate.PROECESS_TYPE_INAUDIT) || notifyParam.getProcessType().equals(ProcessTemplate.PROECESS_TYPE_INAUDIT_FQ) || notifyParam.getProcessType().equals(ProcessTemplate.PROECESS_TYPE_INAUDIT_BP)) {
			// 内审流程
			
			wfType = StatusContexts.WFTYPE_NS;
		
		} else if (notifyParam.getProcessType().equals(ProcessTemplate.PROECESS_TYPE_DEPOSIT) || notifyParam.getProcessType().equals(ProcessTemplate.PROECESS_TYPE_DEPOSIT_FQ)) {
			// 收取保证金、管理费和风险补偿金流程
			
			wfType = StatusContexts.WFTYPE_BZJ;
			
		} else if (notifyParam.getProcessType().equals(ProcessTemplate.PROECESS_TYPE_BANK_REPORT) || notifyParam.getProcessType().equals(ProcessTemplate.PROECESS_TYPE_BANK_REPORT_FQ)) {
			// 银行申报
			
			wfType = StatusContexts.WFTYPE_BRT;
			
		} else if (notifyParam.getProcessType().equals(ProcessTemplate.PROECESS_TYPE_REFUND_MGR_FEE) || notifyParam.getProcessType().equals(ProcessTemplate.PROECESS_TYPE_REFUND_MGR_FEE_FQ)) {
			// 退还保证金、管理费和风险补偿金流程
			
			wfType = StatusContexts.WFTYPE_BACKFEE;
			
		} else if (notifyParam.getProcessType().equals(ProcessTemplate.PROECESS_TYPE_PAY_FQ)) {
			// 付费流程
			
			wfType = StatusContexts.WFTYPE_PAY;
			
		} else if (notifyParam.getProcessType().equals(ProcessTemplate.PROECESS_TYPE_DHK)) {
			
			// 代还款流程
			wfType = StatusContexts.WFTYPE_TYPE_DHK;
			
		} else if (notifyParam.getProcessType().equals(ProcessTemplate.PROECESS_TYPE_BACK_MONEY)) {
			// 回款流程
			
			wfType = StatusContexts.WFTYPE_BACKMONEY;
			
		} else if (notifyParam.getProcessType().equals(ProcessTemplate.PROECESS_TYPE_DCJQ)) {
			// 代偿结清流程
			
			wfType = StatusContexts.WFTYPE_BACKMONEY;
			
		} else if (notifyParam.getProcessType().equals(ProcessTemplate.PROECESS_TYPE_PLACE_ON_FILE) || notifyParam.getProcessType().equals(ProcessTemplate.PROECESS_TYPE_ARCHIVE)) {
			// 归档流程
		
			wfType = StatusContexts.WFTYPE_TYPE_PLACE_ON_FILE;
			
		} else if (notifyParam.getProcessType().equals(ProcessTemplate.PROECESS_TYPE_FINANCE_AUDIT)) {
			// 财务流程
			
			wfType = StatusContexts.WFTYPE_FINANCE;
			
		} else if (notifyParam.getProcessType().equals(ProcessTemplate.PROECESS_TYPE_TQ_PAYMENT)) {
			// 提前还款结清
			
			wfType = StatusContexts.WFTYPE_TQHKJQ;
			
		} else if (notifyParam.getProcessType().equals(ProcessTemplate.PROECESS_TYPE_DC_FED_BACK)) {
			// 代偿分期流程
			wfType = StatusContexts.WFTYPE_TYPE_DC_FED_BACK;
			
		} else if (notifyParam.getProcessType().equals(ProcessTemplate.PROECESS_TYPE_CREDIT_ARCHIVE)) {
			// 征信归档
			
			wfType = StatusContexts.WFTYPE_TYPE_CREDIT_ARCHIVE;
			
		} else if (notifyParam.getProcessType().equals(ProcessTemplate.PROECESS_TYPE_FKZZ)) {
			wfType = StatusContexts.WFTYPE_TYPE_FKZZ;
		} else if (notifyParam.getProcessType().equals(StatusContexts.WF_TYPE_CREDIT_INQUIRY)) {
			wfType = StatusContexts.WFTYPE_TYPE_NZX;
		} else {
			
			return "" ;
		}
		return wfType;
	}
	
	/**
	 * @Title: updateZxzrAndStart
	 * @Description:修改与征信报告有关的征信准入信息，如果征信准入是新建状态，并且启动该流程
	 * @author 张庆奇
	 * @param zxNo
	 * @return void
	 * @throws @date
	 *             2017年10月17日 下午4:45:04
	 */
	private void updateZxzrAndStart(String zxNo) {
		O2oLoanapplyEntity entity = o2oLoanapplyService.findO2oLoanapplyEntityByZxNo(zxNo);
		log.info("新建中的关联征信准入对象", entity);
		boolean isOk = true;
		boolean flag = true;
		if (entity != null) {
			// 启动征信准入流程
			PayMentForm payform = new PayMentForm();
			payform.setLoanapplyNo(entity.getLoanapplyNo());
			flag = checkZxzrstartup(payform);
			
			log.info("是否符合征信准入启动的条件", flag);
			if (flag) {
				isOk = zxzrstartup(payform);
			}
			
			log.info("征信准入是否启动成功", isOk);

			if (!flag || !isOk) {
				// 发短信

				sendMessage(payform);
			}
		}

	}
	
	/**
	 * @Title: checkZxzrstartup
	 * @Description: 校验征信准入是否可以启动流程
	 * @author 张庆奇
	 * @param payform
	 * @return
	 * @return boolean
	 * @throws
	 * @date 2017年10月18日 上午9:24:18
	 */
	public boolean checkZxzrstartup(PayMentForm payform) {
		O2oLoanapplyEntity o2oLoanapplyEntity = o2oLoanapplyService.findById(payform.getLoanapplyNo());

		O2oLoanUserEntity basicEntity = o2oLoanUserService.findById(o2oLoanapplyEntity.getLoanId(),
				o2oLoanapplyEntity.getLoanapplyNo());
		// 检查借款人信息
		String checkLoaner = payMentController.checkZX(basicEntity, o2oLoanapplyEntity);
		if (!checkLoaner.equals(StatusContexts.SUCCESS)) {
			return false;
		}

		if (StringUtil.isEmpty(basicEntity.getZxNo())) {
			log.info("借款人没有关联征信报告");
			return false;
		}

		O2oZxEntity userZx = o2oZxServiceImpl.getEntityById(basicEntity.getZxNo());
		if (!"CLO".equals(userZx.getZxStatus())) {
			log.info("借款人关联的征信报告没有结束");
			return false;
		}

		O2oLoanUserEntityZx o2oLoanUserEntityZx = o2oLoadUserZxServiceImpl.getEntityByZxNo(basicEntity.getZxNo());

		if (o2oLoanUserEntityZx.getZxDate() != null) {
			boolean flag = payMentController.isValid(o2oLoanUserEntityZx.getZxDate(), 30);
			if (!flag) {
				log.info("借款人关联的征信报告不在30天有效期内");
				return false;
			}
		}
		
	/*	// 是否被其他贷款单关联
		boolean byAflag = o2oZxServiceImpl.bcIsSelectedByOther(payform.getLoanapplyNo(), basicEntity.getZxNo());
		if (byAflag) {
			return false;
		}*/

		if (userZx.getZxBank().equals("BC")) {
			// 客户类型是否符合一致
			boolean typeFlag = o2oZxServiceImpl.bcIsSelectedByCustomerType(payform.getLoanapplyNo(),
					basicEntity.getZxNo(), "ZX_JKR");
			if (typeFlag) {
				return false;
			}
		}
		// check贷款信息
		String checkLoanApply = payMentController.checkLoanApply(o2oLoanapplyEntity);
		if (!checkLoanApply.equals(StatusContexts.SUCCESS)) {
			return false;
		}

		O2oLoanUserEntity SpouseEntity = o2oLoanUserService.findSpouseId(o2oLoanapplyEntity.getLoanId(),
				o2oLoanapplyEntity.getLoanapplyNo());
		if (SpouseEntity != null) {

			if (StringUtil.isEmpty(SpouseEntity.getZxNo())) {
				return false;
			}
			O2oZxEntity mateZx = o2oZxServiceImpl.getEntityById(SpouseEntity.getZxNo());
			if (!"CLO".equals(mateZx.getZxStatus())) {
				return false;
			}

			O2oLoanUserEntityZx o2oLoanUserMateEntityZx = o2oLoadUserZxServiceImpl
					.getEntityByZxNo(SpouseEntity.getZxNo());

			if (o2oLoanUserMateEntityZx.getZxDate() != null) {
				boolean flag = payMentController.isValid(o2oLoanUserMateEntityZx.getZxDate(), 30);
				if (!flag) {
					return false;
				}
			}
			
		/*	// 是否被其他贷款单关联
			boolean mateFlag = o2oZxServiceImpl.bcIsSelectedByOther(payform.getLoanapplyNo(), SpouseEntity.getZxNo());
			if (mateFlag) {
				return false;
			}*/

			if (mateZx.getZxBank().equals("BC")) {
				// 客户类型是否符合一致
				boolean mate_typeFlag = o2oZxServiceImpl.bcIsSelectedByCustomerType(payform.getLoanapplyNo(),
						SpouseEntity.getZxNo(), "ZX_PO");
				if (mate_typeFlag) {
					return false;
				}
			}

			// 检查配偶信息
			// check是否编辑配偶关系
			// 1.查询配偶有没存在 2.不存在 ：检测是否有新增配偶关系
			String checkSpouse = payMentController.checkSpouseZX(SpouseEntity.getLoanId());
			if (!checkSpouse.equals(StatusContexts.SUCCESS)) {
				return false;
			}
		}
		return true;

	}
	
	/**
	 * @Title: zxzrstartup
	 * @Description: 启动征信准入流程
	 * @author 张庆奇
	 * @param payform
	 * @return
	 * @return boolean
	 * @throws
	 * @date 2017年10月18日 上午10:41:32
	 */
	public boolean zxzrstartup(PayMentForm payform) {
		O2oLoanapplyEntity o2oLoanapplyEntity = o2oLoanapplyService.findById(payform.getLoanapplyNo());
		WFRequestParam param = new WFRequestParam();
		User user1=employeeService.getUserByNo(o2oLoanapplyEntity.getCreatRo());
		param.setReferId(o2oLoanapplyEntity.getLoanapplyNo());
		param.setReferCode(o2oLoanapplyEntity.getBillCode());
		param.setReferUrl(zxUrl);
		param.setSystemModule(ProcessTemplate.SYSTEM_MODULE_O2O);
		param.setProcessType("PROCESS_ACCESS");
		param.setProcessVersion("v1");
//		User user = UserHolder.getUser();
		param.setAppliedby(o2oLoanapplyEntity.getCreatRo());
		param.setAppliedbyName(user1.getCname());
		param.setOrgNo(o2oLoanapplyEntity.getLtd());
		StringBuffer appliedDes = new StringBuffer("借款人:");
		appliedDes.append(o2oLoanapplyService
				.findLoanUserEntity(o2oLoanapplyEntity.getLoanapplyNo(), o2oLoanapplyEntity.getLoanId())
				.getUserFullName());
		appliedDes.append("，申请金额:");
		java.text.DecimalFormat df = new java.text.DecimalFormat("0.00"); // 格式化，保留两位小数
		appliedDes.append(df.format(o2oLoanapplyEntity.getLoanaMount().doubleValue()));
		param.setAppliedDes(appliedDes.toString());
		log.info("提交征信准入，参数有贷款id：【{}】，贷款编号：【{}】，系统模块：【{}】，流程类型：【{}】，经营平台id：【{}】，贷款摘要信息：【{}】",
				o2oLoanapplyEntity.getLoanapplyNo(), o2oLoanapplyEntity.getBillCode(),
				ProcessTemplate.SYSTEM_MODULE_O2O, param.getProcessType(), o2oLoanapplyEntity.getLtd(),
				appliedDes.toString());
		ModelResult<Boolean> modelResult = workFlowService.instance(param);
		if (modelResult.isSuccess() && modelResult.getModel()) {
			o2oLoanapplyService.updateWorkFlowStatus(StatusContexts.O2O_ZX_BEGIN, o2oLoanapplyEntity.getLoanapplyNo());
			// 启动财务审核流程
			if (o2oLoanapplyEntity.getLoanType().equals(StatusContexts.LOAN_TYPE_BK)
					&& StatusContexts.OPERATION_MODEL_PTDB.equals(o2oLoanapplyEntity.getOperationModel())) {
				O2oFinanceFlowEntity entity = financeFlowService.getByLoanApplyno(payform.getLoanapplyNo());
				if (entity != null && entity.getFlowStatus().equals(StatusContexts.O2O_BANK_NEW)) {
					startUpFinance(payform);
				}
				if (entity == null) {
					startUpFinance(payform);
				}
			}
			return true;
		} else {
			log.error("提交征信准入失败，错误信息{}", modelResult.getDetailStack());
			return false;
		}
		
	}
	
/**
 * @Title: sendMessage
 * @Description: 发送短信
 * @author 张庆奇
 * @param payform
 * @return void
 * @throws
 * @date 2017年10月18日 上午10:22:35
 */
	private void sendMessage(PayMentForm payform) {
		User user = UserHolder.getUser();
		O2oLoanapplyEntity o2oLoanapplyEntity = o2oLoanapplyService.findById(payform.getLoanapplyNo());

		O2oLoanUserEntity o2oLoanUserEntity = o2oLoanapplyService
				.findLoanUserEntity(o2oLoanapplyEntity.getLoanapplyNo(), o2oLoanapplyEntity.getLoanId());
		// 3.失败发送短信
		ModelResult<User> result = sysPermissionService.getSysUserById(o2oLoanapplyEntity.getOperatorNo());// 信贷经理id
		User operator = result.getModel();
		SmsNotifyRequest smsCustomerRequest = new SmsNotifyRequest();
		smsCustomerRequest.setRequestId(o2oLoanapplyEntity.getLoanapplyNo());
		smsCustomerRequest.setBizCode(o2oLoanapplyEntity.getBillCode());
		smsCustomerRequest.setContent("[" + o2oLoanUserEntity.getUserFullName() + "]的征信准入流程自动启动失败，请人工发起征信准入流程。");
		smsCustomerRequest.setRecipientNumber(operator.getMobile());
		smsCustomerRequest.setRequestDateTime(new Date());
		smsCustomerRequest.setSmsSendType(SmsSendType.INSTANT);
		smsCustomerRequest.setSystemCode("业务系统");
		smsCustomerRequest.setReceiveName(user.getCname());
		smsCustomerRequest.setSendName("系统");
		try {
			log.info("征信准入编号：[{}],发送信贷经理手机号:[{}]", o2oLoanapplyEntity.getBillCode(), operator.getMobile());
			com.eascs.notify.constant.ModelResult<SmsNotifyResponse> response = smsNotifier.notify(smsCustomerRequest);
			if (!response.isSuccess()) {

				log.info("征信准入编号：[{}],发送信贷经理短信发送失败原因:{}", o2oLoanapplyEntity.getBillCode(), response.getErrMsg());
			}
		} catch (Exception e) {
			log.error("征信准入编号：[{}],发送信贷经理短信发送异常:{}", o2oLoanapplyEntity.getBillCode(), e.getMessage());

		}
	}
	
	
	
	/**
	 * @Title: startUpFinance
	 * @Description:提交财务流程
	 * @author 张庆奇
	 * @param payform
	 * @return void
	 * @throws
	 * @date 2017年10月18日 上午10:39:45
	 */
	public void startUpFinance(PayMentForm payform) {
		O2oLoanapplyEntity loan = o2oLoanapplyService.findById(payform.getLoanapplyNo());
		
		O2oFinanceFlowEntity entity = financeFlowService.getByLoanApplyno(payform.getLoanapplyNo());
		if (entity == null) {
			entity = new O2oFinanceFlowEntity();
			entity.setBillCode(loan.getBillCode());
			entity.setLoanapplyno(loan.getLoanapplyNo());
			entity.setFlowStatus(StatusContexts.O2O_BANK_NEW);
			entity.setRemark("提交财务审核，贷款id:" + loan.getLoanapplyNo());
			User user = UserHolder.getUser();
			entity.setStartupOperno(user.getNo());
			entity.setStartupOpername(user.getCname());
			financeFlowService.insert(entity);
		} 
		
		WFRequestParam param = new WFRequestParam();
		param.setReferId(loan.getLoanapplyNo());
		param.setReferCode(loan.getBillCode());
		param.setReferUrl(cwshUrl);
		param.setSystemModule(ProcessTemplate.SYSTEM_MODULE_O2O);
		param.setProcessType(String.valueOf(ProcessTemplate.PROECESS_TYPE_FINANCE_AUDIT));
		param.setProcessVersion("v1");
		User user = UserHolder.getUser();
		param.setAppliedby(user.getNo());
		param.setAppliedbyName(user.getCname());
		param.setOrgNo(loan.getLtd());
		StringBuffer appliedDes = new StringBuffer("借款人:");
		appliedDes.append(o2oLoanapplyService.findLoanUserEntity(loan.getLoanapplyNo(), loan.getLoanId()).getUserFullName());
		appliedDes.append("，申请金额:");
		java.text.DecimalFormat df = new java.text.DecimalFormat("0.00"); // 格式化，保留两位小数
		appliedDes.append(df.format(loan.getLoanaMount().doubleValue()));
		param.setAppliedDes(appliedDes.toString());
		log.info("提交财务审核，参数有贷款id：【{}】，贷款编号：【{}】，系统模块：【{}】，流程类型：【{}】，经营平台id：【{}】，贷款摘要信息：【{}】", loan.getLoanapplyNo(), loan.getBillCode(), ProcessTemplate.SYSTEM_MODULE_O2O, param.getProcessType(), loan.getLtd(), appliedDes.toString());
		ModelResult<Boolean> modelResult = workFlowService.instance(param);
		if (modelResult.isSuccess()&& modelResult.getModel()) {
			entity.setStartupTime(new Date());
			entity.setFlowStatus(StatusContexts.O2O_BANK_RUN);
//			o2oPayServiceImpl.updateWftypeStatus(loan.getLoanapplyNo(), StatusContexts.WFTYPE_FINANCE);
			financeFlowService.update(entity);
			
		} else {
			log.error("提交财务流程失败，错误信息{}", modelResult.getDetailStack());
			
		}
	}

	/**
	 * 贷款分类流程通知
	 * @param notifyParam
	 */
	private ModelResult<Boolean> noticeClassify(WFNotifyParam notifyParam) {
		// TODO Auto-generated method stub
		ModelResult<Boolean> model = new ModelResult<Boolean>();
		if (notifyParam.getProcessStatus() == ProcessTaskMain.PROECESS_STATUS_PASS) {
			O2oLoanAbjustTypeFlow generationEntity = o2oClassifySerivce.queryFlowById(notifyParam.getReferId());
			log.info("贷款分类流程通过通知查询：{}", generationEntity.toString());
			generationEntity.setFlowEndTime(new Date());
			generationEntity.setFlowStatus(StatusContexts.WFTYPE_STATUS_CLO);
			generationEntity.setOldLoanType(generationEntity.getNewLoanType());
			generationEntity.setIsNew(StatusContexts.O2O_NO);
			int i = o2oClassifySerivce.updateFlow(generationEntity);
			log.info("贷款分类流程通过通知更新更新是否成功，1为成功：{}", i);
			log.info("贷款分类流程通过通知更新后：{}", generationEntity.toString());
		} else if (notifyParam.getProcessStatus() == ProcessTaskMain.PROECESS_STATUS_TURNED_DOWN) {
			O2oLoanAbjustTypeFlow generationEntity = o2oClassifySerivce.queryFlowById(notifyParam.getReferId());
			log.info("贷款分类流程驳回通知查询：{}", generationEntity.toString());
			generationEntity.setFlowStatus(StatusContexts.WFTYPE_STATUS_NEW);
			int i = o2oClassifySerivce.updateFlow(generationEntity);
			log.info("贷款分类流程驳回通知更新更新是否成功，1为成功：{}", i);
			log.info("贷款分类流程驳回通知更新后：{}", generationEntity.toString());
		} else if (notifyParam.getProcessStatus().equals(ProcessTaskMain.PROECESS_STATUS_REJECT)) {
			O2oLoanAbjustTypeFlow generationEntity = o2oClassifySerivce.queryFlowById(notifyParam.getReferId());
			log.info("贷款分类流程否决通知查询：{}", generationEntity.toString());
			generationEntity.setFlowStatus(StatusContexts.WFTYPE_STATUS_NEW);
			generationEntity.setIsDelete(StatusContexts.O2O_YES);
			int i = o2oClassifySerivce.updateFlow(generationEntity);
			log.info("贷款分类流程否决通知更新更新是否成功，1为成功：{}", i);
			log.info("贷款分类流程否决通知更新后：{}", generationEntity.toString());
		}
		return model;
	}
}
